【常用工具类】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); } }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories