您的位置:首页 > 其它

FAQ_23 设置 Toast 显示时间

2012-11-27 11:39 344 查看
在你写的 android 代码里面是否有下面的示例:

Toast.makeText(getApplicationContext(), "*****", 1).show();

或者

Toast.makeText(getApplicationContext(), "*****", 1000).show();

可以看到这两句代码里面的第三个参数是不一样的,看一下该方法的原型

/**
* Make a standard toast that just contains a text view.
*
* @param context  The context to use.  Usually your {@link android.app.Application}
*                 or {@link android.app.Activity} object.
* @param text     The text to show.  Can be formatted text.
* @param duration How long to display the message.  Either {@link #LENGTH_SHORT} or
*                 {@link #LENGTH_LONG}
*
*/
public static Toast makeText(Context context, CharSequence text, int duration) {
Toast result = new Toast(context);

LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);

result.mNextView = v;
result.mDuration = duration;

return result;
}

第三个参数是用来设置显示时间的。

在 Toast 源码里面,定义

/**
* Show the view or text notification for a short period of time.  This time
* could be user-definable.  This is the default.
* @see #setDuration
*/
public static final int LENGTH_SHORT = 0;

/**
* Show the view or text notification for a long period of time.  This time
* could be user-definable.
* @see #setDuration
*/
public static final int LENGTH_LONG = 1;

这两个常量可以说是一个标示符而不是真正的表示时间的。接着往下看。

本来你是想通过这个参数设置 Toast 的显示时间的,可是 亲们 这样可以吗?

至少在 android 的原生系统(没有被山寨过的)里面,你这样做事达不到真正目的的。

具体可以看一下 com.android.server.NotificationManagerService

private static final int LONG_DELAY = 3500; // 3.5 seconds
private static final int SHORT_DELAY = 2000; // 2 seconds

private void scheduleTimeoutLocked(ToastRecord r, boolean immediate) {
Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
long delay = immediate ? 0
: (r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY);
mHandler.removeCallbacksAndMessages(r);
mHandler.sendMessageDelayed(m, delay);
}

可以看出,时间是固定的 2s~3.5s

,作为 app 开发者你怎么可能更改这个值呢?

如果你想控制 Toast 显示时间,可以自定义一个 Toast 来满足需求。

android api 设计很蛋疼,为什么这个参数不设置为 boolean 类型的?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: