I'm trying to display some text on the screen for a set period of time, similar to a toast, but with the ability to specify the exact time it is on the screen. I'm thinking an alert dialog may work for this, but I can't seem to figure out how to dismiss the dialog automatically.
Can you suggest an alternative to toast notifications in which I can specify the exact time it is displayed?
Thank you!
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);
}
You just need to time calls to Dialog#dismiss()
; for your problem Handler
class would suffice(+1 to Javanator :)).
FYI, there are other classes namely AlarmManager, Timer & TimerTask that can help with timing the runs of your code.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With