定製Toast的顯示時間

背景:

    缺省狀態下,Toast顯示時間大約在1~2秒時間,有時需要讓彈出窗顯示更長的時間。

案例:

    可通過調用CountDownTimeer例來達到此目標。

public class ToastActivity extends Activity
{
    AlertDialog dialog;
   
     static CountDownTimer timer =null;
     Toast toast;
     @Override
        public void onCreate(Bundle savedInstanceState)
        {
                super.onCreate(savedInstanceState);
                

                // creating toast and setting properties

                toast = new Toast(this);
                TextView textView=new TextView(this);
                textView.setTextColor(Color.BLUE);
                textView.setBackgroundColor(Color.TRANSPARENT);
                textView.setTextSize(20);
                textView.setText("This Toast will Display for 20 Seconds in Center of The Screen");
                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);


                toast.setView(textView);
               

               //    Toast Display tTime Settings

               
                // Create the CountDownTimer object and implement the 2 methods
                // show the toast in onTick() method  and cancel the toast in onFinish() method
                // it will show the toast for 20 seconds (20000 milliseconds 1st argument) with interval of 1 second(2nd argument)

 
                timer =new CountDownTimer(20000, 1000)
                {
                    public void onTick(long millisUntilFinished)
                    {
                        toast.show();
                    }
                    public void onFinish()
                    {
                        toast.cancel();
                    }

                }.start();
               
          }
}

通過調用timer.cancel()可以取消Toast的顯示。

結果:

    wKiom1UxonejvRL9AABrMVoJnqc078.jpg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章