如何检查 Android 中的警报是否可见

3
如何检查我的警报是否已在屏幕上显示?
 AlertDialog.Builder alert = new AlertDialog.Builder(this);

 alert.show();

我可以在我的代码中添加一个标志来设置和重置状态,但如果已经有一个可重复使用的方法呢?


请明确一点,您想要检查警报是否正在显示吗? - MysticMagicϡ
是的,完全正确 @MysticMagic - user3833308
alert.isShowing() 方法。 - Rustam
4个回答

12

AlertDialog.Builder类中没有isShowing()方法,但是Dialog类中有这个方法。

AlertDialog.Builder

Dialog

AlertDialog.Builder类用于创建AlertDialog。一旦你有了一个AlertDialog的实例,你可以通过调用它的isShowing()方法来确定它是否仍在显示。

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
AlertDialog alertDialog = alertDialogBuilder.create();

if(!alertDialog.isShowing()){   
  //if its visibility is not showing then show here 
   alertDialog.show();       
 }else{
  //do something here... if already showing       
  }

3

是的,你可以使用isShowing();方法来检查它。

这个方法在Android文档中有记录。

但在你的情况下,你需要先捕获由AlertDialog.Builder创建的AlertDialog。
因此,你的代码应该像这样:

AlertDialog alertDialog;

function showDialog() {
    if(alertDialog == null) { 
        //Initial Creation will always show 
        //or you can just use create() if you don't want to show it at initial creation
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        AlertDialog alertDialog = alert.show();
    else {
        if(alertDialog.isShowing()) {
             alertDialog.hide();
        } else {
             alertDialog.show();
        }
    }
}

1
但是我想根据其可见性决定是否显示,我可以在调用show()之前做到这一点吗? - user3833308

2
请使用以下内容:
AlertDialog alertDialog = alert.create();

//to check if its being shown
if(!alertDialog.isShowing()){
    //do something
    alertDialog.show();
}

如果当前显示了该警告对话框,它将返回true。因此,在您的情况下,请检查它是否返回false,然后显示它。

希望这能有所帮助。


0

您可以使用对话框的isShowing方法,或者可以维护一个标志,例如在创建警报对话框时标志为0,在显示后将其设置为1。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接