我试图在屏幕上显示一段时间的文字,类似于吐司,但能够指定它在屏幕上的确切时间。我认为警报对话框可能适用于此,但我似乎无法弄清楚如何自动关闭对话框。
您能否建议一种替代吐司通知,我可以在其中指定显示的确切时间?
谢谢!
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 :(得分:8)
您只需要拨打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);
}
答案 1 :(得分: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);
希望这个帮助:)