在使用工作中经常使用Toast,如果用户连续点击很多下按钮,可能Toast显示一两分钟也不会消失,这就给我们的用户造成了困扰。以下是解决办法:
private int num = 0;//连续点击的次数
private static Toast toast;
private Toast getInstanceToast(Context context) {
if (toast == null) {
synchronized (TestActivity.this) {
if (toast == null) {
toast = new Toast(context);
}
}
}
return toast;
}
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
num++;
Toast toast = getInstanceToast(TestActivity.this);
LayoutInflater inflater = LayoutInflater.from(TestActivity.this);
View v = inflater.inflate(R.layout.toast_layout, null);// 得到加载view
TextView tv = (TextView) v.findViewById(R.id.tv);
tv.setText("第" + num + "次点击");
toast.setView(v);
toast.show();
}
});