Android hides the dialog after the set time, for example, a user-defined time interval

I try to display some text on the screen for a certain period of time, like a toast, but with the ability to specify the exact time that it is on the screen. I think a warning dialog may work for this, but I cannot figure out how to automatically cancel the dialog.

Can you offer an alternative to toast notifications in which I can indicate the exact time it was displayed?

Thanks!

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); } 
+4
source share
2 answers

You just need the time to call Dialog#dismiss() ; for your problem, the Handler class would be sufficient (+1 to Javanator :)).

FYI, there are other classes: AlarmManager , Timer, and TimerTask , which can help determine when your code will run.

EDIT:

Change your code to:

 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); } 
+8
source
  // Make your Main UIWorker Thread to execute this statement Handler mHandler = new Handler(); 

Do something like this when your code should reject the dialog.

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

Hope this help :)

+5
source

Source: https://habr.com/ru/post/1341491/


All Articles