![](/img/trans.png)
[英]Android: Display a toast message after a custom time when a button is clicked
[英]Android hide dialog after set time, like a custom time-interval toast
我試圖在屏幕上顯示一些文本一段時間,類似於吐司,但能夠指定它在屏幕上的確切時間。 我認為警報對話框可能適用於此,但我似乎無法弄清楚如何自動關閉對話框。
你能建議一個替代吐司通知,我可以指定它顯示的確切時間嗎?
謝謝!
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);
}
你只需要調用Dialog#dismiss()
; 對於你的問題Handler
類就足夠了(+1到Javanator :))。
僅供參考,還有其他類,即AlarmManager , Timer和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);
}
// 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);
希望這個幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.