软件编程
位置:首页>> 软件编程>> Android编程>> Android 自定义 Toast 显示时间

Android 自定义 Toast 显示时间

作者:lqh  发布时间:2022-01-22 23:22:06 

标签:Android,Toast,时间

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;
}
}

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

来源:http://www.123si.org/android/240.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com