開發過Android的童鞋都會遇到一個問題,就是在打印Toast提示時,如果短時間內觸發多個提示,就會造成Toast不停的重復出現,直到被觸發的Toast全部顯示完為止。這雖然不是什么大毛病,但在用戶體驗上聽讓人發狂的。本篇博文就是介紹怎么自定義Toast提示,不僅能完美的解決上述問題,而且還能自定義提示UI。
先看一下效果圖(左邊是普通的toast提示,右邊是自定義的):
光看效果圖,可能還感受不到什么不同,點擊多次之后就會發現文章開頭說的情況。
接着看一下自定Toast的開發步驟:
·第一步:准備自定義Toast的布局文件。
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:id="@+id/container" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:orientation="vertical" > 7 8 <TextView 9 android:id="@+id/txt_toast" 10 android:layout_width="wrap_content" 11 android:layout_height="wrap_content" 12 android:padding="5dp" 13 android:background="#ccc" 14 android:textColor="#fff" /> 15 16 </LinearLayout>
·第二步:編寫一個獨立的自定義Toast類或者方法,方便調用。
1 public void myToast(String msg){ 2 if(toast == null){ 3 toast = new Toast(this); 4 } 5 toast.setDuration(0); 6 toast.setGravity(Gravity.CENTER, 0, 0); 7 LayoutInflater inflater = this.getLayoutInflater(); 8 LinearLayout toastLayout = (LinearLayout)inflater.inflate(R.layout.toast, null); 9 TextView txtToast = (TextView)toastLayout.findViewById(R.id.txt_toast); 10 txtToast.setText(msg); 11 toast.setView(toastLayout); 12 toast.show(); 13 }
·第三步:調用普通Toast提示,和自定義Toast,查看效果。布局文件只有兩個按鈕,比較簡單就不貼了。
1 bnToast.setOnClickListener(new OnClickListener() { 2 @Override 3 public void onClick(View arg0) { 4 Toast.makeText(getApplicationContext(), "普通toast提示", Toast.LENGTH_SHORT).show(); 5 } 6 }); 7 bnMyToast.setOnClickListener(new OnClickListener() { 8 @Override 9 public void onClick(View arg0) { 10 myToast("自定義toast提示"); 11 } 12});