Andorid中的Toast是一种比较常见的系统提示框。因为常见,所以常常忽略了其细节。经常使用的人都知道,Toast不能在没有Looper的线程显示提示框。那么下面通过源码来探究其原理。
先来看看其makeText方法:
public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
return makeText(context, null, text, duration);
}
public static Toast makeText(@NonNull Context context, @Nullable Looper looper,
@NonNull CharSequence text, @Duration int duration) {
Toast result = new Toast(context, looper);//创建对象
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;
}
好像看不出来什么端倪。再来看看show方法:
public void show() {
if (mNextView =