I'm new to the development scene and I'm just trying my hand at fragments. I have an onClick event defined in one of my fragment XML files, but when I click the button my app crashes.
I've surmised that this happens because my onClick event is defined in my fragment and not my MainActivity
, so I was just wondering what is the best practice to get my buttons working. Should I just pass the button along to my fragment, or should I move my onClick event to my MainActivity
then reference it from my fragment?
***************** this is the code ****************
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:gravity="center"
android:layout_weight="1.5">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_marginRight="5dp"
android:gravity="right"
android:layout_weight="2">
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="150dp"
android:id="@+id/txt_textInputLayout_three"
android:layout_height="wrap_content"
app:startIconDrawable="@drawable/ic_baseline_calendar_today_24">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/txt_from_user1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="From"
android:onClick="openDataPicker_from"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_marginLeft="5dp"
android:gravity="left"
android:layout_weight="2">
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="150dp"
android:id="@+id/txt_textInputLayout_four"
android:layout_height="wrap_content"
app:startIconDrawable="@drawable/ic_baseline_calendar_today_24">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/txt_to_user1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="To"
android:onClick="openDatePicker_to"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
</LinearLayout>
Java file***
public void openDatePicker_from(View view) {
dataPickerDialog_from.show();
}
public void openDatePicker_to(View view) {
dataPickerDialog_to.show();
}
this the error
java.lang.IllegalStateException: Could not find method openDataPicker(View) in a parent or ancestor Context for android:onClick attribute defined on view class com.google.android.material.textfield.TextInputEditText with id 'txt_from_user1'
at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:5368)