Android Dialog, keep dialog open when button is pressed

后端 未结 7 1347
故里飘歌
故里飘歌 2020-11-30 01:59

I would like to keep my dialog open when I press a button. At the moment it\'s closing.

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

builder         


        
7条回答
  •  [愿得一人]
    2020-11-30 02:50

    You do not need to create a custom class. You can register a View.OnClickListener for the AlertDialog. This listener will not dismiss the AlertDialog. The trick here is that you need to register the listener after the dialog has been shown, but it can neatly be done inside an OnShowListener. You can use an accessory boolean variable to check if this has already been done so that it will only be done once:

    /*
     * Prepare the alert with a Builder.
     */
    AlertDialog.Builder b = new AlertDialog.Builder(this);
    
    b.setNegativeButton("Button", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {}
    });
    this.alert = b.create();
    
    /*
     * Add an OnShowListener to change the OnClickListener on the
     * first time the alert is shown. Calling getButton() before
     * the alert is shown will return null. Then use a regular
     * View.OnClickListener for the button, which will not 
     * dismiss the AlertDialog after it has been called.
     */
    
    this.alertReady = false;
    alert.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            if (alertReady == false) {
                Button button = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //do something
                    }
                });
                alertReady = true;
            }
        }
    });
    

提交回复
热议问题