解决Toast不断显示问题

    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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值