4

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

您能否建议我可以指定显示确切时间的 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);


}
4

2 回答 2

9

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


}
于 2011-02-27T06:46:29.907 回答
5
 // Make your Main UIWorker Thread to execute this statement
 Handler mHandler = new Handler(); 

在您的代码需要关闭对话框的地方执行类似的操作。

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

希望这有帮助:)

于 2011-02-27T05:09:48.480 回答