4

トーストのように、一定期間画面にテキストを表示しようとしていますが、画面に表示されている正確な時間を指定する機能があります。アラートダイアログがこれで機能するかもしれないと思っていますが、ダイアログを自動的に閉じる方法がわからないようです。

トースト通知の代わりに、表示される正確な時間を指定できる方法を提案できますか?

ありがとうございました!

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

Dialog#dismiss();への呼び出しの時間を計る必要があります。問題Handlerのクラスは十分です(Javanatorに+1 :))。

参考までに、コードの実行のタイミングを調整するのに役立つ他のクラス、つまり、AlarmManagerTimer 、 TimerTaskがあります。

編集:

コードを次のように変更します。

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 に答える