【问题标题】:How to set a cancel button in Progress Dialog?如何在进度对话框中设置取消按钮?
【发布时间】:2020-01-23 21:49:49
【问题描述】:

我想在我的ProgressDialog 中设置一个取消按钮。以下是我的代码:

myDialog = new ProgressDialog(BaseScreen.this);
myDialog.setMessage("Loading...");
myDialog.setCancelable(false);
myDialog.show();

我想在这个ProgressDialog 上设置一个带有onClickListener 的按钮。 我试过这段代码:

myDialog.setButton("Cancel", new OnClickListener() {        
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub          
        myDialog.dismiss();
    }
});

但它不起作用。我也尝试了其他类似的听众,但仍然没有成功。 我该如何解决这个问题?

【问题讨论】:

    标签: android


    【解决方案1】:

    您使用的setButton 方法已弃用(尽管它应该仍然有效)。此外,您可能希望在显示对话框之前添加按钮。试试:

    myDialog = new ProgressDialog(BaseScreen.this);
    myDialog.setMessage("Loading...");
    myDialog.setCancelable(false);
    myDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            myDialog.dismiss();//dismiss dialog
        }
    });
    myDialog.show();
    

    【讨论】:

    • 仅供参考,dialog.dismiss()onClick 侦听器中不是必需的,因为它会自动关闭对话框。实际上,此方法不允许您阻止对话框被关闭。
    【解决方案2】:

    确保在致电myDialog.show();之前先致电myDialog.setButton
    如果您只需要在单击按钮时关闭对话框,您也可以使用myDialog.setButton("Cancel", (DialogInterface.OnClickListener) null);

    【讨论】:

      【解决方案3】:

      检查一下

      private void createCancelProgressDialog(String title, String message, String buttonText)
      {
          cancelDialog = new ProgressDialog(this);
          cancelDialog.setTitle(title);
          cancelDialog.setMessage(message);
          cancelDialog.setButton(buttonText, new DialogInterface.OnClickListener() 
          {
              public void onClick(DialogInterface dialog, int which) 
              {
                  // Use either finish() or return() to either close the activity or just the dialog
                  return;
              }
          });
          cancelDialog.show();
      }
      

      然后只需在活动的其他地方使用简单的调用方法

      createCancelProgressDialog("Loading", "Please wait while activity is loading", "Cancel");
      

      【讨论】:

      • 4.3以上取消
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      • 2014-11-25
      • 1970-01-01
      • 2010-11-10
      • 1970-01-01
      相关资源
      最近更新 更多