如何关闭AlertDialog android

时间:2017-07-26 02:01:28

标签: java android alertdialog

我的问题是当我选择一个项目AlertDialog解雇

alertDialog = new AlertDialog.Builder(getActivity());
alertDialog
        .setSingleChoiceItems(ageArr, 1, btnSelectItem)
        .setPositiveButton(R.string.dialog_ok, btnPositiveAgeDialog)
        .setNegativeButton(R.string.dialog_cancel, null)
        .show();

我的对话框点击正面看起来是什么。

private DialogInterface.OnClickListener btnSelectItem = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        selectedIndexAge = which;
    }
};

我尝试将侦听器设置为null,但它仍未关闭 我需要它,因为我想知道选择了哪个项目

3 个答案:

答案 0 :(得分:0)

就这么说吧

itemView.setOnClickListener(null);

您可以使用hasOnClickListeners()的实现来了解从android.view.View类中获取的侦听器的状态

 public boolean hasOnClickListeners() {
        ListenerInfo li = mListenerInfo;
        return (li == null && li.mOnClickListener == null);
    }

使用以下链接进行进一步修改

Set listener instance in fragment on application restore

答案 1 :(得分:0)

试试这个

 dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
  {            
      @Override
      public void onClick(View v)
      {
          Boolean wantToCloseDialog = false;
          //Do stuff, possibly set wantToCloseDialog to true then...
          if(wantToCloseDialog)
              dialog.dismiss();
          //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
      }
  });

答案 2 :(得分:0)

其他一些必须关闭你的AlertDialog。以下是我认为重复了您发布的最低要求的程序,选择其中一个项目不会关闭对话框。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String[] values = new String[]{ "one", "two", "three", "four" };

        DialogInterface.OnClickListener choiceListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "selected index: " + which, Toast.LENGTH_SHORT).show();
            }
        };

        DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "positive button", Toast.LENGTH_SHORT).show();
            }
        };

        new AlertDialog.Builder(this)
                .setSingleChoiceItems(values, 1, choiceListener)
                .setPositiveButton("ok", positiveListener)
                .setNegativeButton("cancel", null)
                .show();
    }
}