片段警报对话框中的自定义取消按钮未处理单击事件

Custom cancel button in fragment's AlertDialog's click event not handled

我创建了一个对话框,其布局以及取消和提交按钮都是完全自定义的,这要归功于布局。我想处理两个按钮的点击 - 特别是,我们在这个问题中考虑取消按钮。

问题

单击取消按钮时,不会执行单击事件处理程序。

实施

解释

我创建了一个对话片段。在其中,我使用对话框构建器来创建我的对话框(按照官方文档的建议)。我为取消按钮设置了点击处理程序并取消了其中的对话框。

取消按钮是可点击的(在布局文件中指定)。因此,事件通常会很好地触发。就是好像没处理好。

来源

DialogFragment.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(即:片段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 的 "customizable" 区域。 (你可以通过先膨胀一个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;