Android设置时间后隐藏对话框,就像自定义时间间隔吐司一样

Nat*_*ugh 4 user-interface android toast android-alertdialog

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

你能建议一个替代吐司通知,我可以指定它显示的确切时间吗?

谢谢!

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);


}
Run Code Online (Sandbox Code Playgroud)

Sam*_*muh 9

你只需要打电话给Dialog#dismiss(); 对于你的问题Handler类就足够了(+1给Javanator :)).

仅供参考,还有其他类,即AlarmManager,TimerTimerTask,可以帮助您计算代码的运行时间.

编辑:

将您的代码更改为:

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);


}
Run Code Online (Sandbox Code Playgroud)


Jav*_*tor 5

 // Make your Main UIWorker Thread to execute this statement
 Handler mHandler = new Handler(); 
Run Code Online (Sandbox Code Playgroud)

做这样的事情你的代码需要解雇对话框.

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

希望这个帮助:)