Toast是Android中最常見的反饋機(jī)制,和Dialog不一樣的是,它沒有焦點(diǎn),只能做簡(jiǎn)單的提示.雖然Google為我們提供了功能更強(qiáng)大的SnackBar,但是如果你無法說服你的產(chǎn)品經(jīng)理接受它,那還是老老實(shí)實(shí)使用Toast.
關(guān)于Toast的源碼就不看了,其實(shí)就是直接往window上面直接添加了一個(gè)View.不過Toast在使用的時(shí)候,還是存在一些問題:
- 如果連續(xù)產(chǎn)生了多個(gè)Toast,那么你會(huì)發(fā)現(xiàn)它會(huì)一個(gè)接一個(gè)的慢慢顯示,要很久才能消失.這是因?yàn)門oast都在一個(gè)隊(duì)列里面,只有上一個(gè)消失了,下一個(gè)才能顯示,顯然這樣的體驗(yàn)不太友好.
為了避免上面的問題,我們需要提供一個(gè)方法,創(chuàng)建單例的Toast.這里為了方便,我直接繼承了Toast,代碼不多,就直接貼出來了:
public class SuperToast extends Toast {
private TextView message;
private ImageView image;
private SuperToast(Context context) {
super(context);
setDuration(Toast.LENGTH_SHORT);
}
volatile static SuperToast toast;
public synchronized static SuperToast init() {
if (toast == null) {
synchronized (SuperToast.class) {
if (toast == null) {
toast = new SuperToast(App.getContext());
}
}
}
return toast;
}
public SuperToast duration(int duration) {
super.setDuration(duration);
return this;
}
public void textNormal(CharSequence s){
text(s,0);
}
public void textSuccess(CharSequence s){
text(s,1);
}
public void textError(CharSequence s){
text(s,2);
}
private void text(CharSequence s, int type){
if(getView() == null){
View v = View.inflate(App.getContext(),R.layout.default_toast, null);
image = (ImageView) v.findViewById(R.id.image);
message = (TextView)v.findViewById(R.id.message);
setView(v);
}
if(type == 0 && image.getVisibility() != View.GONE){
image.setVisibility(View.GONE);
}else if(type == 1){
if(image.getVisibility() != View.VISIBLE){
image.setVisibility(View.VISIBLE);
}
image.setImageResource(android.R.drawable.stat_notify_chat);
}else if(type == 2){
if(image.getVisibility() != View.VISIBLE){
image.setVisibility(View.VISIBLE);
}
image.setImageResource(android.R.drawable.stat_notify_error);
}
message.setText(s);
show();
}
}
代碼很簡(jiǎn)單,沒什么需要解釋的地方. 需要注意的是,為免單例模式引起內(nèi)存泄漏,這里的Context使用的是Application.前面說過,toast是直接添加到window上面的,不依賴于Activity,所以使用Application構(gòu)建是沒有問題的.
這樣我們就可以通過以下的方式使用了
SuperToast.init().textNormal("a");
SuperToast.init().textSuccess("呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵");
SuperToast.init().textError("addafhsdhshashsdhsgahshsh");
效果如下
S61017-155757.jpg