Android 在设置时间后隐藏对话框,就像自定义时间间隔 toast

标签 android user-interface android-alertdialog toast

我正在尝试在屏幕上显示一些文本一段时间,类似于 toast ,但能够指定它在屏幕上的确切时间。我认为警告对话框可能适用于此,但我似乎无法弄清楚如何自动关闭该对话框。

您能否建议一种 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);


}

关于Android 在设置时间后隐藏对话框,就像自定义时间间隔 toast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5131559/

相关文章:

android - 对话框中的可点击链接

java - 当第二次打开 AlertDialog 时应用程序崩溃

Android:在 Android 2.3 中,对话框不是全屏或没有奇怪背景的 AlertDialog

java - 为什么这个gui不更新?

android espresso 在运行测试之前登录一次

android - 如何在Xamarin Forms中保存通过推送通知接收的数据

Android:没有 Activity 的类中的警报对话框

android - 带有菜单按钮的手机上 ActionBar 的正确用户体验?

java - 简单的静音问题?

android - 如果单击新图像,则将先前选择的图像替换为原始图像