这里有新鲜出炉的精品教程,程序狗速度看过来!
Android 是一种基于 Linux 的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由 Google 公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用 "安卓" 或 "安致"。
这篇文章主要介绍了 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.phperz.com/article/17/0818/337534.html