How can I show a toast for a specific duration?

前端 未结 12 2158
自闭症患者
自闭症患者 2020-12-08 01:08

This is the way I have to show the Toast for 500 milliseconds. Though, it\'s showing more than a second.

Toast.makeText(LiveChat.this, \"Typing\         


        
12条回答
  •  Happy的楠姐
    2020-12-08 01:40

    Accepted answer is correct but in my case the toast blink(show & hide) can be noticed..

    I got a solution where Toast is not blinking and you can customise the Toast as well.

    Lets begin,

    1) Create a class Named LongToast.

    class LongToast {
    
    private LongToast() {}
    
    static void makeLongToast(Context context,String text, long durationInMillis) 
    {
    
     final Toast toastMessage = new Toast(context);
    
     //Creating TextView.
     TextView textView = new TextView(context);
    
     //Setting up Text Color.
     textView.setTextColor(Color.parseColor("#fafafa"));
    
     //Setting up Text Size.
     textView.setTextSize(17);
    
     //Setting up Toast Message Text.
     textView.setText(text);
    
     //Add padding to Toast message.
     textView.setPadding(20, 20, 20, 23);
    
     //Add Gravity TextView.
     textView.setGravity(Gravity.CENTER);
    
     //Adding TextView into Toast.
     toastMessage.setView(textView);
    
     //Access toast message as View.
     View toastView = toastMessage.getView();
    
     //Set Custom Background on Toast.
     toastView.setBackgroundResource(R.drawable.test);
    
    
     new CountDownTimer(durationInMillis, 1000)
      {
       public void onTick(long millisUntilFinished)
       {
        toastMessage.show();
       }
      public void onFinish()
       {
        toastMessage.cancel();
       }
    
      }.start();
     }
    }
    

    2) Create a drawable xml for customising the Toast.

    
    
     
     
     
     
    
    

    you can customise the toast as per your need.

    3) Finally Calling Toast.

    LongToast.makeLongToast(this,"whatever you want",10000);//duration in seconds
    

    ref : click here to check

    Thanks!!.

提交回复
热议问题