這次把自定義的魔爪伸向了Toast。效果就是下面這樣
廢話不多說誓军,直接上代碼
public class ToastUtil {
private Context context;
private Toast toast;
public ToastUtil(Context context) {
this.context = context.getApplicationContext();
toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
}
public boolean showToast(String str) {
if (toast.getView().getParent() != null) {
if (toast.getView().getContentDescription().equals(str)) {
return false;
} else {
toast.cancel();
toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);
toast.show();
}
} else {
toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);
toast.show();
}
return true;
}
public boolean showToastWithImg(String str, Drawable imgRes) {
if (toast.getView().getParent() != null) {
toast.cancel();
}
toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(16);
textView.setText(str);
textView.setPadding(80, 0, 80, 0);
imgRes.setBounds(0, 0, imgRes.getMinimumWidth(), imgRes.getMinimumHeight());
textView.setCompoundDrawables(imgRes, null, null, null);
textView.setBackground(context.getResources().getDrawable(R.drawable.shape_round_toast));
toast.setView(textView);
toast.show();
return false;
}
}
原理就是在<code>toast.setView()</code>這里,簡單粗暴。
把toast里的View替換為TextView栓撞,Textview就隨便我們玩了,設置圖標和背景手到擒來,甚至可以用自定義的view瓤湘。瓢颅。
本例就是寫一個簡單的shape作為textView的bg,或者用逼格高一點的圖片都行弛说。隨性著來
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<size
android:width="10dp"
android:height="50dp"/>
<solid android:color="@color/colorPrimary_alpha"/>
<corners android:radius="100dp"/>
</shape>
代碼中使用
先實例化工具類
toastUtil = new ToastUtil(getApplicationContext());
在需要吐司的地方調用寫好的方法
帶圖標的
toastUtil.showToastWithImg("讀取系統(tǒng)信息",
getResources().getDrawable(R.drawable.ic_device_info_toast));
不帶圖標的
toastUtil.showToast("啦啦啦");