【问题标题】:How can I handle outside click of my custom alertDialog?如何处理自定义 alertDialog 的外部点击?
【发布时间】:2018-11-29 14:11:01
【问题描述】:

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

当我在 AlertDialog 外部按下时出现问题,因为它在没有向 recyclerView 发送通知的情况下关闭了 AlertDialog,因此 recyclerView 不会从 swipeMode 返回。

如何处理 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();

        }
    });


}

【问题讨论】:

标签: android android-alertdialog


【解决方案1】:

有两种方法,禁用取消或处理对话框取消(“单击对话框外”)。

您可以避免对话框被取消,如下所示:

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

处理取消操作或“点击对话框外”:

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

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

【讨论】:

  • 实际上我还试图使用 .setOnCancelListener 但它不起作用但我只是通过在设置布局之前放置监听器来修复它。谢谢
猜你喜欢
  • 1970-01-01
  • 2023-04-11
  • 2015-02-17
  • 2015-05-09
  • 1970-01-01
  • 2018-11-11
  • 1970-01-01
  • 2017-09-03
  • 2020-07-16
相关资源
最近更新 更多