2011-02-27 41 views
4

我試圖在屏幕上顯示一段文字一段時間,類似於吐司,但能夠指定確切的時間在屏幕上。我在想一個警告對話框可能適用於此,但我似乎無法弄清楚如何自動關閉對話框。設置時間後的Android隱藏對話框,如自定義時間間隔敬酒

你可以建議一個替代吐司通知,我可以在其中指定確切的時間顯示?

謝謝!

static DialogInterface dialog = null; 
public void toast(String text, int duration) { 

    final AlertDialog.Builder builder = new AlertDialog.Builder(gameplay); 

    LayoutInflater inflater = (LayoutInflater) gameplay.getSystemService(gameplay.LAYOUT_INFLATER_SERVICE); 
    View layout = inflater.inflate(R.layout.tutorial, (ViewGroup)gameplay.findViewById(R.id.layout_root)); 
    ((TextView)layout.findViewById(R.id.message)).setText(text); 

    builder 
     .setView(layout); 


    builder.show(); 

    if (dialog!=null){ 
     dialog.cancel(); 
     dialog.dismiss(); 
    } 

    dialog = builder.create(); 


    Handler handler = null; 
    handler = new Handler(); 
    handler.postDelayed(new Runnable(){ 
     public void run(){ 
      dialog.cancel(); 
      dialog.dismiss(); 
     } 
    }, 500); 


} 
+0

@Javanator,感謝指出了這一點,我...我不知道我能/應該這樣做。 – 2011-03-01 04:09:16

回答

8

你只需要一次調用Dialog#dismiss();對於你的問題Handler類就足夠了(Javanator :) +1)。

僅供參考,還有其他類即AlarmManagerTimer & TimerTask可以用定時代碼的運行幫助。

編輯:

更改您的代碼:

static DialogInterface dialog = null; 
public void toast(String text, int duration) { 

    final AlertDialog.Builder builder = new AlertDialog.Builder(gameplay); 

    LayoutInflater inflater = (LayoutInflater) gameplay.getSystemService(gameplay.LAYOUT_INFLATER_SERVICE); 
    View layout = inflater.inflate(R.layout.tutorial, (ViewGroup)gameplay.findViewById(R.id.layout_root)); 
    ((TextView)layout.findViewById(R.id.message)).setText(text); 

    builder 
     .setView(layout); 


    //builder.show(); commented this line 
// I don't understand the purpose of this if block, anyways 
// let it remain as is at the moment 
    if (dialog!=null){ 
     dialog.cancel(); 
     dialog.dismiss(); 
    } 

    dialog = builder.create().show(); 


    Handler handler = null; 
    handler = new Handler(); 
    handler.postDelayed(new Runnable(){ 
     public void run(){ 
      dialog.cancel(); 
      dialog.dismiss(); 
     } 
    }, 500); 


} 
+0

AlarmManager,Timer&TimerTask也是一個不錯的選擇我同意+1 – Javanator 2011-02-27 07:05:28

+0

你能用實際的代碼更新你的問題嗎? – Samuh 2011-02-28 06:14:56

+0

我已經添加了代碼,我希望這可以幫助你,幫助我! – 2011-03-01 04:14:26

5
// Make your Main UIWorker Thread to execute this statement 
Handler mHandler = new Handler(); 

做這樣的事情在以往任何時候你的代碼需要關閉該對話框。

// this will dismiss the dialog after 2 Sec. set as per you 
mHandler.postDelayed(new Runnable() { 
    @Override 
    public void run() {  
     dialog.dismiss(); 
    } 
},2000L); 

希望這有助於:)

+0

這似乎並不按我期望的方式工作。我用代碼編輯了我的原始帖子。 – 2011-03-01 04:14:49