我们在开发过程中,并不会去用系统提供的默认的Toast样式,很多情况下需要去自己定制Toast的显示,这篇文章就是定制Toast的显示。
先上效果图
效果图这里只是简单的展示了如何去自定义Toast的布局,如果你需要定制其他类型的布局,可以参考本篇,毕竟都是这个套路。
直接上代码,相信聪明的你肯定能看懂的
ToastUtil.class
public class ToastUtil {
/**
* refreshToast:在屏幕下部显示Toast提示信息. <br/>
*
* @param context - 上下文
* @param msg - 提示消息
* @param lastTime - 持续时间,0-短时间,LENGTH_SHORT;1-长时间,LENGTH_LONG;
*/
public static void showToast(Context context, String msg, int lastTime) {
int resId = R.drawable.common_blue_btn_normal;
View view = View.inflate(context, R.layout.common_toast, null);
Toast toast = new Toast(context);
toast.setView(view);
((TextView) view.findViewById(R.id.common_toast_tv)).setText(msg);
toast.setDuration(lastTime);
toast.show();
}
/**
* refreshToast:解决Toast重复显示,显示不及时. <br/>
*
* @param context - 上下文
* @param msg - 提示消息
* @param lastTime - 持续时间,0-短时间,LENGTH_SHORT;1-长时间,LENGTH_LONG;
*/
private static Toast mytoast;
private static Handler mHandler = new Handler();
private static Runnable r = new Runnable() {
@Override
public void run() {
mytoast.cancel();
}
};
public static void refreshToast(Context context, String msg, int lastTime) {
if (mytoast != null) {
mHandler.removeCallbacks(r);
}
int resId = R.drawable.common_blue_btn_normal;
View view = View.inflate(context, R.layout.common_toast, null);
TextView tvMsg = ((TextView) view.findViewById(R.id.common_toast_tv));
if (mytoast == null) {
mytoast = new Toast(context);
tvMsg.setText(msg);
mHandler.postDelayed(r, 3500);
} else {
tvMsg.setText(msg);
}
mytoast.setView(view);
mytoast.setDuration(lastTime);
mytoast.show();
}
}
common_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/common_toast_ll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/common_toast_blue_bg"
android:orientation="horizontal" >
<TextView
android:id="@+id/common_toast_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textColor="#ffffff"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
/>
</LinearLayout>
用法
ToastUtil.refreshToast(activity, "定制化Toast", 1);
ToastUtil.showToast(activity, "定制化Toast", 1);
看了实现方式,很简单吧,那就赶快定制化自己的Toast吧!!!
网友评论