Toast(一)基础介绍和分析

Toast是Android中用来显示显示信息的一种机制,和Dialog不一样的是,Toast是没有焦点的,而且Toast显示的时间有限,过一定的时间就会自动消失。

1.使用Toast.makeText(context, text, duration).show();

2.new Toast();

View view = getLayoutInflater().inflate(R.layout.toast, null);
  TextView textView = (TextView) view.findViewById(R.id.textview);
  textView.setText("What a nice day!");
  Toast toast = new Toast(this);
  toast.setDuration(Toast.LENGTH_LONG);
  toast.setView(view);
  toast.show();

为什么要用setView()呢?而不能toast.setText(“”)呢?

既然可以直接使用makeText产生toast查看makeText源码:

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

其也是把view设置给toast。
如果同时显示多个Toast信息提示框,系统会将这些信息提示框放到队列中,等前一个信息提示框关闭之后,才会显示下一个信息提示框。

查看show()方法:

    public void show() {
        if (mNextView == null) {
            throw new RuntimeException("setView must have been called");
        }

        INotificationManager service = getService();
        String pkg = mContext.getPackageName();
        TN tn = mTN;
        tn.mNextView = mNextView;

        try {
            service.enqueueToast(pkg, tn, mDuration);
        } catch (RemoteException e) {
            // Empty
        }
    }

service.enqueueToast(pkg, tn, mDuration);就是把当前Toast加入到Toast队列中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值