【发布时间】:2021-08-04 05:28:32
【问题描述】:
我是开发领域的新手,我只是在尝试片段。我在我的片段 XML 文件中定义了一个 onClick 事件,但是当我单击该按钮时,我的应用程序崩溃了。
我推测发生这种情况是因为我的 onClick 事件是在我的片段中定义的,而不是在我的 MainActivity 中,所以我只是想知道让我的按钮工作的最佳做法是什么。我应该将按钮传递给我的片段,还是应该将我的 onClick 事件移动到我的 MainActivity 然后从我的片段中引用它?
谢谢各位。 *代码强>
<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 文件***
public void openDatePicker_from(View view) {
dataPickerDialog_from.show();
}
public void openDatePicker_to(View view) {
dataPickerDialog_to.show();
}
这是错误
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)
【问题讨论】:
标签: java android android-fragments