如何处理自定义 alertDialog 的外部点击?

How can I handle outside click of my custom alertDialog?

实际上,在我的应用程序中,当我滑动 RecyclerView 时,如果我正在使用其中的按钮进行操作,它会打开一个自定义的 AlertDialog,一切都按预期进行。

当我在 AlertDialog 外部按下时出现问题,因为它关闭了 AlertDialog 而没有向 recyclerView 发送通知,因此 recyclerView 不会从滑动模式返回。

如何处理 AlertDialog 外的点击?我只需要添加这个句柄 exampleAdapter.notifyItemChanged.

这是我的 AlertDialog 代码:

public void customAllertQuantity(final int position){

    AlertDialog.Builder mBuilder = new AlertDialog.Builder(this);

    @SuppressLint("InflateParams") View mView = getLayoutInflater().inflate(R.layout.alert_quantity, null);

    final EditText quantita = mView.findViewById(R.id.editTextQTA);

    Button buttonPiu = mView.findViewById(R.id.btnPLUS);
    Button buttonMeno = mView.findViewById(R.id.btnMINUS);
    ImageButton save = mView.findViewById(R.id.saveButton);

    quantita.setText(String.valueOf(itemCassas.get(position).getQuant()));

    mBuilder.setView(mView);
    final AlertDialog dialog = mBuilder.create();
    dialog.show();

    buttonPiu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            quantita.setText(String.valueOf((Integer.parseInt(quantita.getText().toString()) + 1)));
        }
    });

    buttonMeno.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(Integer.parseInt(quantita.getText().toString()) > 1){
                quantita.setText(String.valueOf((Integer.parseInt(quantita.getText().toString()) - 1)));
            }else{
                Log.i("LOG","QTA = 1");
                //
            }
        }
    });

    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            double prezz = itemCassas.get(position).getImporto();
            itemCassas.get(position).setQuant(Integer.parseInt(quantita.getText().toString()));
            itemCassas.get(position).setPrice(prezz *  itemCassas.get(position).getQuant());
            TotalPrice();
            exampleAdapter.notifyItemChanged(position);
            dialog.dismiss();

        }
    });


}

有两种方法,禁用取消或处理对话框取消 ("click outside of dialog")。

您可以通过以下方式避免对话框被取消:

mBuilder.setView(mView);
mbuilder.setCancelable(false);
final AlertDialog dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);

处理取消操作或 "click outside of dialog":

builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialogInterface) {
            //send notification to adapter
        }
    });

注意: 对话框可能因取消或选择提供的选项之一以外的原因而关闭。如果您有兴趣收听所有关闭对话框的情况,请使用 setOnDismissListener