Toast的簡單封裝

Toast是Android中最常見的反饋機制,和Dialog不一樣的是,它沒有焦點,只能做簡單的提示.雖然Google為我們提供了功能更強大的SnackBar,但是如果你無法說服你的產品經理接受它,那還是老老實實使用Toast.


關于Toast的源碼就不看了,其實就是直接往window上面直接添加了一個View.不過Toast在使用的時候,還是存在一些問題:

  • 如果連續產生了多個Toast,那么你會發現它會一個接一個的慢慢顯示,要很久才能消失.這是因為Toast都在一個隊列里面,只有上一個消失了,下一個才能顯示,顯然這樣的體驗不太友好.

為了避免上面的問題,我們需要提供一個方法,創建單例的Toast.這里為了方便,我直接繼承了Toast,代碼不多,就直接貼出來了:

public class SuperToast extends Toast {

     private TextView message;

     private ImageView image;

     private SuperToast(Context context) {
         super(context);
         setDuration(Toast.LENGTH_SHORT);
     }

     volatile static SuperToast toast;

     public synchronized static SuperToast init() {
          if (toast == null) {
              synchronized (SuperToast.class) {
                 if (toast == null) {
                     toast = new SuperToast(App.getContext());
                 }
              }
          }
          return toast;
     }

     public SuperToast duration(int duration) {
         super.setDuration(duration);
         return this;
     }

     public void textNormal(CharSequence s){
          text(s,0);
     }

     public void textSuccess(CharSequence s){
          text(s,1);
     }

     public void textError(CharSequence s){
          text(s,2);
     }

     private void text(CharSequence s, int type){
           if(getView() == null){
               View v = View.inflate(App.getContext(),R.layout.default_toast, null);
               image = (ImageView) v.findViewById(R.id.image);
               message = (TextView)v.findViewById(R.id.message);
               setView(v);
           }
           if(type == 0 && image.getVisibility() != View.GONE){
               image.setVisibility(View.GONE);
           }else if(type == 1){
               if(image.getVisibility() != View.VISIBLE){
                  image.setVisibility(View.VISIBLE);
               }
               image.setImageResource(android.R.drawable.stat_notify_chat);
           }else if(type == 2){
               if(image.getVisibility() != View.VISIBLE){
                  image.setVisibility(View.VISIBLE);
               }
               image.setImageResource(android.R.drawable.stat_notify_error);
           }
           message.setText(s);
           show();
      }
 }

代碼很簡單,沒什么需要解釋的地方. 需要注意的是,為免單例模式引起內存泄漏,這里的Context使用的是Application.前面說過,toast是直接添加到window上面的,不依賴于Activity,所以使用Application構建是沒有問題的.

這樣我們就可以通過以下的方式使用了

  SuperToast.init().textNormal("a");
  SuperToast.init().textSuccess("呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵");
  SuperToast.init().textError("addafhsdhshashsdhsgahshsh");

效果如下

S61017-155757.jpg

代碼在這里

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容