Android Toastの表示時間を長く/短くする 【Android TIPS】
ToastはToast.LENGTH_SHORT指定時に約2秒、Toast.LENGTH_LONG指定時に約4秒間 表示されます。
DDMSからキャプチャを取る際に4秒だと短すぎてうまく取れなかったり、
エラーメッセージを表示するのには2秒では長すぎたりすることもあります。
表示される時間を指定できたら便利だなーと思ってクラスを作ってみました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | package com.example; import android.content.Context; import android.os.AsyncTask; import android.os.Handler; import android.widget.Toast; public class CustomToast extends AsyncTask<String, Integer, Integer> implements Runnable{ private Toast toast = null ; private long duration = 0 ; private Handler handler = new Handler(); public static CustomToast makeText (Context context, int resId, long duration){ CustomToast ct = new CustomToast(); ct.toast = Toast.makeText(context, resId, Toast.LENGTH_SHORT); ct.duration = duration; return ct; } public static CustomToast makeText (Context context, CharSequence text, long duration){ CustomToast ct = new CustomToast(); ct.toast = Toast.makeText(context, text, Toast.LENGTH_SHORT); ct.duration = duration; return ct; } public void show() { if (duration > 2000 ){ for ( int i = 0 ; i < duration - 2000 ; i += 2000 ) { handler.postDelayed( this , i); } handler.postDelayed( this , duration - 2000 ); } else { this .execute(); } } public void run() { toast.show(); } @Override protected Integer doInBackground(String... params) { try { Thread.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } return 0 ; } @Override protected void onPreExecute() { toast.show(); } @Override protected void onPostExecute( final Integer i) { toast.cancel(); } } |
以下、使用方法。
第3引数に表示時間(ms)を指定します。
1 2 3 4 5 | // 10秒間Toastを表示 CustomToast.makeText( this , R.string.text, 10 * 1000 ).show(); // 0.5秒間Toastを表示 CustomToast.makeText( this , "ここに出力される文字を指定" , 500 ).show(); |
表示時間が短い場合は、AsyncTaskを使いToastを表示させたい時間の間だけSleepしたのちToastをキャンセル、
表示時間が長い場合は、handler.postDeley()を使い、同じToastを何度も表示させています。
参考にしたHP:
http://d.hatena.ne.jp/shepherdMaster/20110418/1303165701
http://blog.kumarn.com/2012/04/android-toast.html