Android Dialog, keep dialog open when button is pressed

后端 未结 7 1363
故里飘歌
故里飘歌 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:54

    Thanks Sogger for your answer, but there is one change that we have to do here that is, before creating dialog we should set possitive button (and negative button if there is need) to AlertDialog as traditional way, thats it.

    Referenced By Sogger.

    Here is the sample example ...

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Test for preventing dialog close");
            builder.setTitle("Test");
    
            builder.setPositiveButton("OK", new OnClickListener() {
    
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
    
                }
            });
        builder.setNegativeButton("Cancel", new OnClickListener() {
    
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
    
                }
            });
    
            final AlertDialog dialog = builder.create();
            dialog.show();
            //Overriding the handler immediately after show is probably a better approach than OnShowListener as described below
            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.
                      }
                  });
    
            dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener()
              {            
                  @Override
                  public void onClick(View v)
                  {
                      Boolean wantToCloseDialog = true;
                      //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.
                  }
              });
    

提交回复
热议问题