如何检查我的警报是否已在屏幕上显示?
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.show();
我可以在我的代码中添加一个标志来设置和重置状态,但如果已经有一个可重复使用的方法呢?
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.show();
我可以在我的代码中添加一个标志来设置和重置状态,但如果已经有一个可重复使用的方法呢?
AlertDialog.Builder类中没有isShowing()方法,但是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
}
是的,你可以使用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();
}
}
}
AlertDialog alertDialog = alert.create();
//to check if its being shown
if(!alertDialog.isShowing()){
//do something
alertDialog.show();
}
如果当前显示了该警告对话框,它将返回true
。因此,在您的情况下,请检查它是否返回false
,然后显示它。
希望这能有所帮助。
您可以使用对话框的isShowing方法,或者可以维护一个标志,例如在创建警报对话框时标志为0,在显示后将其设置为1。
alert.isShowing()
方法。 - Rustam