Android hide dialog after set time, like a custom time-interval toast
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 = (Lay开发者_如何学编程outInflater) 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);
}
// Make your Main UIWorker Thread to execute this statement
Handler mHandler = new Handler();
Do something like this where ever your code need to dismiss 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 :)
精彩评论