2014-10-22 66 views
1

如何檢查我的警報是否已在屏幕上顯示?如何檢查警報是否可見android

AlertDialog.Builder alert = new AlertDialog.Builder(this); 

alert.show(); 

我可以在我的代碼設置和重置把一個標誌保持狀態,但如果已經有,我可以重新使用的方法?

+0

請清楚後。你想檢查警報是否正在顯示? – 2014-10-22 05:46:44

+0

yes確切@MysticMagic – user3833308 2014-10-22 05:47:30

+0

'alert.isShowing()'方法。 – Rustam 2014-10-22 05:51:30

回答

9

上有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  
    } 
1

是的,你可以用isShowing();方法 它也記錄在Android Documentation

但在你的情況下,你需要捕獲由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 2014-10-22 05:52:11

2

使用此:

AlertDialog alertDialog = alert.create(); 

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

它將返回true如果當前正被顯示的警告對話框。所以在你的情況下,檢查它是否返回false,然後顯示它。

希望它有幫助。

0

可以使用的對話框isShowing方法或可以保持標誌當你創建警報對話框標誌爲0等,並展示使它1.