Android 自定义 Toast 显示时间

实现代码:

package com.wm.realname.util;import android.content.Context;import android.os.Handler;import android.view.View;import android.widget.Toast;/** * Toast自定义显示时间 * 使用方法 * 1.先初始化类 MyToast myToast = new MyToast(this); * 2.显示消息 myToast.setText("要显示的内容"); //设置要显示的内容 *  myToast.show(8000); //传入消息显示时间,单位毫秒,最少2000毫秒,并且只能是2000的倍数。 *  传入0时会一直显示,只有调用 myToast.cancel();时才会取消。 * 3.取消消息显示 myToast.cancel(); * */public class ToastUtil { private Context mContext = null; private Toast mToast = null; private Handler mHandler = null; private int duration = 0; private int currDuration = 0; private final int DEFAULT = 2000; private Runnable mToastThread = new Runnable() {  public void run() {   mToast.show();   mHandler.postDelayed(mToastThread, DEFAULT); // 每隔2秒显示一次   if (duration != 0) {    if (currDuration <= duration) {     currDuration += DEFAULT;    } else {     cancel();    }   }  } } public ToastUtil(Context context) {  mContext = context;  currDuration = DEFAULT;  mHandler = new Handler(mContext.getMainLooper());  mToast = Toast.makeText(mContext, "", Toast.LENGTH_LONG); } public void setText(String text) {  mToast.setText(text); } public void show(int duration) {  this.duration = duration;  mHandler.post(mToastThread); } public void setGravity(int gravity, int xOffset, int yOffset) {  mToast.setGravity(gravity, xOffset, yOffset); } public void setDuration(int duration) {  mToast.setDuration(duration); } public void setView(View view) {  mToast.setView(view); } public void cancel( ) {  mHandler.removeCallbacks(mToastThread);// 先把显示线程删除  mToast.cancel();// 把最后一个线程的显示效果cancel掉,就一了百了了  currDuration = DEFAULT; }}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

更多相关文章

  1. android WebSocketClient和TCP协议Socket
  2. android 通过滚动条改变图片显示
  3. android闹钟(五):实现闹钟功能
  4. Android(安卓)消息机制 你了解多少
  5. Android高级进阶之路【六】Android(安卓)Framework解析
  6. android下载封装类
  7. Android(安卓)技巧 - notification center 发出通知时显示文字
  8. android 图片水平显示,类Gallery效果
  9. android 监听短信和来电

随机推荐

  1. Android(安卓)按钮控制ViewPager左右翻页
  2. Android6.0 PackageManagerService(PMS)-
  3. Android Studio 基础 之 如何取消使用 An
  4. Android屏蔽软键盘并且显示光标的实例详
  5. Android(安卓)Day08四大组件之服务Servic
  6. Connection to https://dl-ssl.google.co
  7. android小知识(1)
  8. Google宣布Android暂停开源
  9. 图解 Android 动画中 android:pivotX 和
  10. android studio 开发 cordova plugin(组件