【问题标题】:Android Alert Dialog - how to hide the OK button after it being pressedAndroid Alert Dialog - 如何在按下 OK 按钮后隐藏它
【发布时间】:2011-05-16 13:08:23
【问题描述】:

我一直在开发一个 Android 应用程序。

我想在用户按下 OK 按钮后隐藏它,因为在计算发生时对话框窗口会在前台停留几秒钟。

这是代码:

    new AlertDialog.Builder(this)
    .setMessage("This may take a while")
    .setPositiveButton("OK", new android.content.DialogInterface.OnClickListener() {                
        @Override
        public void onClick(DialogInterface dialog, int which) {
                       // hide the OK button - how?
                       // a lot of computation
        }
    })
    .show(); 

我怎样才能做到这一点?

P.S.:我对处理计算的更高级技术不感兴趣(例如:进度对话框、多线程)。

谢谢。

【问题讨论】:

  • 如果您打算在 UI 线程上进行长时间运行的计算,请做好准备,当您的应用触发应用无响应错误时,用户会给您很多负面反馈。
  • 为了防止“应用程序没有响应”错误,您应该在AsyncTask 中运行您的计算。

标签: android android-alertdialog


【解决方案1】:
.setPositiveButton("OK", new android.content.DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
         ((AlertDialog)dialog).getButton(which).setVisibility(View.INVISIBLE);
         // the rest of your stuff
    }
})

【讨论】:

  • 但是看起来你的设计在这部分并不完美。使用AsyncTaskProgressDialog 可能会更好。 AsyncTask 允许在后台线程上运行长时间计算,因此您的主 UI 线程不会被阻塞,因此应用程序不会获得 ANR。
  • 有没有办法禁用按钮取决于对话框栏上的文本字段?
  • @akdurmus:我相信应该有办法,但是请就此提出一个新问题。
  • 我不会让它消失,而是禁用它。 .setEnabled( false ) 对用户来说,震动更少。此外,当然在ASyncTask 中使用AlertDialog 而不仅仅是AlertDialog
【解决方案2】:
setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
        dialog.dismiss();

其中dialogDialogInterface

【讨论】:

    【解决方案3】:

    对于尝试禁用 AlertDialog 上的“肯定”按钮的其他人,这些解决方案中的很多现在似乎都不起作用 - 一旦您调用 create on,您就无法获取对该按钮的引用AlertDialog.Builder,它只会返回 null。

    所以它应该可用的一个地方是onResume,所以我让它工作的方式是这样的:

    var positiveButton: Button? = null
    
    override fun onResume() {
        super.onResume()
        if (positiveButton == null) {
            positiveButton = (dialog as AlertDialog).getButton(AlertDialog.BUTTON_POSITIVE)
        }
    }
    

    这样,当片段运行时,您应该有一个可用的引用,因此您可以在需要禁用它时调用positiveButton.isEnabled = false

    请注意您的状态,重新创建的片段可能有一些复选框或其他内容,但它还没有 positiveButton 引用,它会在 onResume 中重新运行该代码。因此,如果您需要进行任何初始化(例如在用户选择一个选项之前禁用按钮),请确保调用一个检查当前状态并决定是否应启用按钮的函数。不要以为它只是空白!

    【讨论】:

      【解决方案4】:

      您可以将按钮的可见性设置为不可见。

      ok.setVisibility(View.INVISIBLE);
      

      【讨论】:

      • 但是我怎样才能得到'ok'变量呢?
      猜你喜欢
      • 2023-04-06
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      相关资源
      最近更新 更多