ToastUtils(工具类)
2018-10-23 本文已影响0人
沧海丶一枝梅
前言:
- Android项目中常用来提醒用户某个事件发生了的一种可视化组件就是Toast。
使用:
- 添加Toast的方法也很简单,使用Toast.makeText()方法来设置显示的内容以及时间。
Toast.makeText(context, massage, duration);
参数 context 为当前的上下文环境
参数 massage 为当前要显示的内容
参数 duration 用来设置显示时间的长短 Toast.LENGTH_SHORT和Toast.LENGTH_LONG
- 切记使用Toast.show()的方法将Tosat显示出来。
Toast.makeText(context, massage, duration).show();
问题:
- Toast在项目开发中发现的问题
1.Toast在activity销毁后,还在显示
2.当Toast响应点击事件时,如果用户连续点击,就会导致多个Toast排队等待依次显示
在UI界面隐藏或者销毁前取消Toast显示
public static void cancel() {
if (toast != null) {
toast.cancel();
toast = null;
}
}
解读源码得知,每次调用makeText()的方法都是通过handler发送异步任务来调用远程通知服务显示通知的,这样自然就造成了排队显示的现象。由此可想如果我们在显示期间只修改同一个Tosat对象的显示内容,这样显示的都是最后一次的内容效果,刚好Tosat也为我们提供了Tosat.setText(massage)方法来修改显示的内容,等待问题迎刃而解。
if (toast == null) {
toast = Toast.makeText(context, massage, duration);
} else {
toast.setText(massage);
toast.setDuration(duration);
}
封装:
- ToastUtils.java
public class ToastUtils {
private ToastUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
private static Context context;
// Toast对象
private static Toast toast;
// 文字显示的颜色 <color name="white">#FFFFFFFF</color>
private static int messageColor = R.color.white;
/**
* 在Application中初始化ToastUtils.init(this)
*
* @param context
*/
public static void init(Context context) {
ToastUtils.context = context.getApplicationContext();
}
/**
* 发送Toast,默认LENGTH_SHORT
*
* @param resId
*/
public static void show(int resId) {
showToast(context, context.getString(resId), Toast.LENGTH_SHORT);
}
private static void showToast(Context context, String massage, int duration) {
// 设置显示文字的颜色
SpannableString spannableString = new SpannableString(massage);
ForegroundColorSpan colorSpan = new ForegroundColorSpan(ContextCompat.getColor(context, messageColor));
spannableString.setSpan(colorSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
if (toast == null) {
toast = Toast.makeText(context, spannableString, duration);
} else {
toast.setText(spannableString);
toast.setDuration(duration);
}
// 设置显示的背景
View view = toast.getView();
view.setBackgroundResource(R.drawable.toast_frame_style);
// 设置Toast要显示的位置,水平居中并在底部,X轴偏移0个单位,Y轴偏移200个单位,
toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 200);
toast.show();
}
/**
* 在UI界面隐藏或者销毁前取消Toast显示
*/
public static void cancel() {
if (toast != null) {
toast.cancel();
toast = null;
}
}
}
- toast_frame_style.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="1000dp"/>
<solid android:color="@color/colorPrimaryDark"/>
<stroke
android:width="0.5dp"
android:color="@color/colorAccent"/>
<padding
android:top="10dp"
android:bottom="10dp"
android:left="10dp"
android:right="10dp"/>
</shape>
备注:
修改Tosat的文本颜色和背景颜色有很多种方法,我只是选了一种自己常用的。
如果发现内容哪里有纰漏或者说错的地方,请多加指点,小小码农,正在努力。