您的位置:首页 > 移动开发 > Android开发

【常用工具类】ToastUtil

2016-01-14 21:36 330 查看
Toast 是安卓系统中,用户误操作时或某功能执行完毕时,对用户的一种提示,它没有焦点,并在一定时间内会消失,但用户连续误操作(如登录时,密码错误)多次时,则会有多个 Toast 被创建,系统会把这些 Toast 放进队列中,等待上个Toast 显示完毕,接着显示下一个,那么用户则会看到多次 Toast 提示,无论你退出软件与否,这样给用户的体验则大打折扣,所以我们需要做的是,只有 Toast 为空时,才重新 new,分析到这里,大家应该明白怎么去写了吧。第二个问题是,为了使 Toast 能跟我们自己的应用风格搭配,常常需要我们自定义 Toast 显示,接下来,我们就来解决这两个问题:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:background="@drawable/toast_bg"
android:padding="10dp" >

<TextView
android:id="@+id/toast_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center"
android:maxLines="2"
android:textColor="@color/text"
android:textSize="14sp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:text="网络连接失败"/>

</RelativeLayout>


public class ToastUtil {

private static Toast mToast;
private static Handler mHandler = new Handler();
private static Runnable mRunnable = new Runnable() {
public void run() {
mToast.cancel();
mToast = null;              // toast 隐藏后,将其置为 null
}
};

public static void showToast(Context context, String message, int duration) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_toast, null);          //自定义布局
TextView text = (TextView) view.findViewById(R.id.toast_message);
text.setText(message);          //显示的提示文字
mHandler.removeCallbacks(mRunnable);
if (mToast == null) {           // 只有 mToast == null 时才重新创建,否则只需更改提示文字
mToast = new Toast(context);
mToast.setDuration(Toast.LENGTH_LONG);
mToast.setGravity(Gravity.BOTTOM, 0, 150);
mToast.setView(view);
}
mHandler.postDelayed(mRunnable, duration);  // 延迟 duration 事件隐藏 toast
mToast.show();
}

// 获取 String.xml 中的提示信息
public static void showToast(Context context, int strId, int duration) {
showToast(context, context.getString(strId), duration);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息