我创建了一个对话框,其布局以及取消和提交按钮都是完全自定义的,这要归功于布局。我想处理两个按钮的点击 - 特别是,我们在这个问题中考虑取消按钮。
问题
单击取消按钮时,不会执行单击事件处理程序。
实现
说明
我创建了一个对话框 fragment 。在其中,我使用对话框构建器来创建我的对话框(按照官方文档的建议)。我为取消按钮设置了点击处理程序并取消了其中的对话框。
取消按钮是可点击的(在布局文件中指定)。因此,事件通常会很好地触发。只是好像没有处理。
来源
对话框 fragment .java
注意:在下文中,未显示输出“ok”,而显示按钮引用的输出是。这意味着设置点击事件处理程序的函数已执行(并且按钮是从布局中正确获取的),但点击事件处理程序甚至在执行点击时也未执行。
public class DialogFragment extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(Objects.requireNonNull(getActivity()));
builder.setView(R.layout.dialog);
View view = LayoutInflater.from(this.getContext()).inflate(R.layout.dialog, null);
Dialog dialog = builder.create();
setCancelButtonListener((Button) Objects.requireNonNull(view.findViewById(R.id.button_cancel)), dialog);
return dialog;
}
private void setCancelButtonListener(Button button, final Dialog dialog) {
System.out.println(button);
button.setOnClickListener( new Button.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("ok");
dialog.cancel();
}
});
}
}
dialog.xml(即: fragment XML 布局中的取消按钮)
<Button
android:clickable="true"
android:id="@+id/button_cancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:background="@drawable/background_button"
android:text="@string/cancel"
android:textColor="@color/colorRoyalRedLight"
app:layout_constraintEnd_toStartOf="@+id/button3"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/text_4" />
问题
为什么按钮点击事件没有处理?如何让它发挥作用?
最佳答案
查看代码中的这两行:
builder.setView(R.layout.dialog);
View view = LayoutInflater.from(this.getContext()).inflate(R.layout.dialog, null);
在这里,您将布局的资源 ID 提供给 AlertDialog.Builder
,这样它将使用它来填充 AlertDialog
的“可定制”区域。 (您可以通过先膨胀一个 View
然后调用 AlertDialog.Builder.setView(View)
来实现相同的效果)
接下来,让 LayoutInflater
通过再次膨胀相同的布局文件 创建一个View
。这个新的 View
可以通过 onCreateDialog()
中的局部变量 view 访问,但它永远不会添加到任何 ViewGroup
所以它永远不会真正显示出来。因为不能点击此 View
中包含的 Button
,所以它的 OnClickListener
永远不会触发。
所以你应该像这样设置AlertDialog
:
AlertDialog.Builder builder = new AlertDialog.Builder(Objects.requireNonNull(getActivity()));
View view = LayoutInflater.from(this.getContext()).inflate(R.layout.dialog, null);
builder.setView(view);
Dialog dialog = builder.create();
setCancelButtonListener((Button) Objects.requireNonNull(view.findViewById(R.id.button_cancel)), dialog);
return dialog;
关于android - 未处理 fragment 的 AlertDialog 的单击事件中的自定义取消按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52745909/