FAQ_23 设置 Toast 显示时间

在你写的 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 类型的?







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值