解决Toast的多次点击多次触发不停显示弹框的问题

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();
    }
}
View Code

完整的代码如下:

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();
    }
}
View Code

 

 

posted @ 2020-10-12 21:57  wangheq  阅读(755)  评论(0编辑  收藏  举报