Toast在Android开发中是很常用的,但是如果我们在多次点击的时候会不停的触发Toast不停显示弹框,以至于在进入其他活动的时候,上一个活动的Toast还在不停的显示,这种设计是极其不合理的,对用户不友好。所以我们需要将Toast进行重写封装。只让Toast显示一次。
public class toast{
private static Context context = null;
private static Toast toast = null;
public static void showToast(Context context,String text) {
if (toast == null) {
toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
} else {
toast.setText(text);
toast.setDuration(Toast.LENGTH_SHORT);
}
toast.show();
}
}
完整的代码如下:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.b1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toast.showToast(MainActivity.this,"显示弹框");
}
});
}
}
class toast {
private static Context context = null;
private static Toast toast = null;
public static void showToast(Context context, String text) {
if (toast == null) {
toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
} else {
toast.setText(text);
toast.setDuration(Toast.LENGTH_SHORT);
}
toast.show();
}
}
![](https://img-blog.csdnimg.cn/img_convert/c3ec310a14c1362ca2e76100a168ae0f.png)