本篇文章主要介绍了"Android源码解析——Toast",主要涉及到方面的内容,对于Android开发感兴趣的同学可以参考一下:
简介Toast是一种向用户快速提供少量信息的视图。当它显示时,它会浮在整个应用层的上面,并且不会获取到焦点。它的设计思想是能够向用户展示些信息,但又能尽量不显得...
简介
Toast是一种向用户快速提供少量信息的视图。当它显示时,它会浮在整个应用层的上面,并且不会获取到焦点。它的设计思想是能够向用户展示些信息,但又能尽量不显得唐突。本篇我们来研读一下Toast的源码,并探明它的显示及隐藏机制。
源码解析
Toast
我们从Toast的最简单调用开始,它的调用代码是:
Toast.makeText(context,"Show toast",Toast.LENGTH_LONG).show();
在上面的代码中,我们是先调用Toast
的静态方法来创建一个Toast
,然后调用其show()
方法将其显示出来。其中makeText
的源码如下:
publicstatic Toast makeText(Context context, CharSequence text, @Duration 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;
}
可以看到只是new出一个Toast,并设置要显示的View及时间。这里默认使用的Toast布局transient_notification.xml
也在SDK,代码如下:
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:background="?android:attr/toastFrameBackground"><TextView
android:id="@android:id/message"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:layout_gravity="center_horizontal"android:textAppearance="@style/TextAppearance.Toast"android:textColor="@color/bright_foreground_dark"android:shadowColor="#BB000000"android:shadowRadius="2.75"
/>LinearLayout>
它只是一个简单的LinearLayout套一个TextView。顺便说一句,从布局上我们可以知道这个Toast的背景颜色是可以配置的,通过在theme中配置toastFrameBackground
属性。
回到Toast,我们来看一下它的属性定义及构造方法。
publicclassToast {final Context mContext;
final TN mTN;
int mDuration;
View mNextView;
publicToast(Context context) {
mContext = context;
mTN = new TN();
mTN.mY = context.getResources().getDimensionPixelSize(
com.android.internal.R.dimen.toast_y_offset);
mTN.mGravity = context.getResources().getInteger(
com.android.internal.R.integer.config_toastDefaultGravity);
}
它的属性很简单,只有四个,分别是上下文对象mContext
,TN
对象mTN
,表示显示时长的mDuration
,以及表示将要显示的视图mNextView
。在它的构造方法中,初始化mTN
及它的两个成员变量。
留意一下Toast中显示的View的命名为mNextView
。
我们再往下翻一下Toast的一些成员方法,会发现它的许多行为的实现,都是把值赋给了mTN所对应的属性,比如设置gravity
,水平外边距,x轴或y轴的偏移等等。而它的show
及cancel
方法,也都是通过其来实现,如下: