在进行android开发时,我们经常用到Toast来给用于进行提示,大部分情况下android中提供给我们的默认方法基本上能够解决问题。但问题是有些用户嫌android原生的Toast不好看,想定义属于他们自己风格的Toast。考虑到别具一格的Toast确实能给用于耳目一新的感觉,因此我们也有了仔细去分析它实现细节的理由哈。先来看看demo中显示的android原生的Toast风格。
public void startToast(View view){
Toast.makeText(MainActivity.this, "您点击了Button按钮",
Toast.LENGTH_SHORT).show();
}
为了一探究竟,我们进入makeText()方法中,我们来看看android中是怎样来实现该方法的:
//android官方的makeText方法
public static 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;
}
从代码中可以看出,其实就是用LayoutInflater系统方法导入了一个android中内置的布局文件,我们再来看看这个原生的布局文件:
//com.android.internal.R.layout.transient_notification布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns: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>
com.android.internal.R.id.message就是这上面的TextView控件的ID。makeText方法中传入的text的参数赋值给了TextView。接着又把View赋值给了Toast的成员函数并返回了一个Toast类型的对象。说白了这里其实就是通过makeText方法构造出了一个Toast类型的对象,然后将android中内置的布局文件转成一个View对象以及显示的时间传给Toast的成员变量。
再来看看show()方法的实现原理。//show()方法
public void show() {
if (mNextView == null) {
throw new RuntimeException("setView must have been called");
}
INotificationManager service = getService();
String pkg = mContext.getOpPackageName();
TN tn = mTN;