在日常的开发中,我们经常会使用到 Dialog、PopupWindow、Toast 等,为了防止重复点击多次弹出,我们可以使用单例、或者定时器,配合 isShow() 的方法能很好的解决这个问题。
那么系统的弹窗呢?比如 Intent 分享,我们没有弹窗打开关闭的回调,也不能做弹窗的单例,那我们要怎么解决这个问题呢?笔者介绍两种方式。
1. 使用定时器,设置开关
private boolean canShow = true;
private CountDownTimer showTimer = new CountDownTimer(500,500) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
canShow = true;
}
};
private void showDialog(){
if(!canShow){
return;
}
// Intent 分享
Intent intent = new Intent();
...
canShow = false;
showTimer.start();
}
我们可以写个定时器,点击分享后 0.5 s 之内点击无效,0.5 s 后放开开关,这样基本能够解决,那还有没有更好的解决办法呢?
2. 使用 Activity 的生命周期,设置开关
我们知道,当 Activity 上面打开一个透明主题的 Activity 或者 DialogActivity 或者 Dialog 等,Activity 的 onPause() 会被调用,Dialog 消失时 onResume() 会被调用,所以我们可以通过 Activity 的生命周期开控制 Dialog 的展示。
private boolean canShow = true;
@Override
protected void onResume() {
super.onResume();
canShow = true;
}
@Override
protected void onPause() {
super.onPause();
canShow = false;
}
private void showDialog(){
if(!canShow){
return;
}
// Intent 分享
Intent intent = new Intent();
...
}