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队列中。