Toast是Android中用来显示信息的一种机制,和Dialog不一样的是,Toast是没有焦点,而且Toast显示的时间有限,过一定的时间就会自动消失。
Toast一般用来提示用户的误操作。但是如果同时显示多个Toast信息提示框,系统会将这些Toast信息提示框放到队列中,等前一个Toast信息提示框关闭后才会显示下一个Toast信息提示框。当用户在某些情况下,误操作多次时,使用 Toast提示会出现很多个Toast依次显示,在页面上停留很长时间,用户体验很不好!
为了解决这一问题,每次创建Toast时先做一下判断,如果前面有Toast在显示,只需调用Toast中的setText()方法将要显示的信息替换即可。
public class ToastUtil {
private static Toast mToast;
public static void showToast(Context context, CharSequence charSequence) {
View mView = LayoutInflater.from(context).inflate(
R.layout.top_tips_pop, null);
TextView popTips = (TextView) mView.findViewById(R.id.pop_text);
popTips.setText(charSequence);
if(mToast == null){
mToast = new Toast(context);
}
mToast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 10);
mToast.setDuration(Toast.LENGTH_SHORT);
mToast.setView(mView);
mToast.show();
}
}
注意:每次显示都需要重新获取View,不然会报:This Toast was not created with Toast.makeText()错误。
top_tips_pop.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="756dp"
android:layout_height="70dp"
android:gravity="top"
android:layout_marginTop="1dp"
android:background="@drawable/pop_bg"
android:orientation="vertical" >
<TextView
android:id="@+id/pop_text"
android:layout_width="756dp"
android:layout_height="70dp"
android:text="@string/lowBattaryTip"
android:gravity="center_horizontal"
android:textSize="28sp"
android:singleLine="true"
/>
</LinearLayout>