在安卓系统中防止双击按钮的最佳方法是什么?
当前回答
如果按钮做的唯一一件事是启动一个新活动,这个问题可以通过“singleTop”活动启动模式和在意图上设置FLAG_ACTIVITY_CLEAR_TOP来解决。这种方法不适用于复杂活动的层次结构,但适用于简单的树状应用程序结构。
其他回答
加上Jim的回答,代码可以变得更简洁:
fun View.setOnSingleClick(onClick: () -> Unit) {
var lastClickTime = 0L
setOnClickListener {
if (currentTimeMillis() > lastClickTime + 750) onClick()
lastClickTime = currentTimeMillis()
}
}
用法:
aView.setOnSingleClick { }
对我来说,只有记住时间戳并检查它(距离上次点击超过1秒)才有帮助。
在点击的时候保存最后一次点击的时间可以避免这个问题。
i.e.
private long mLastClickTime = 0;
...
// inside onCreate or so:
findViewById(R.id.button).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// mis-clicking prevention, using threshold of 1000 ms
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000){
return;
}
mLastClickTime = SystemClock.elapsedRealtime();
// do your magic here
}
}
Setting the button as clickable false upon clicking and true once it is desired to make the button clickable again is the right approach. For instance, consider the following scenario: you are making a service call upon click of a button and once the service is done you want to display a dialog. For this, once the button is clicked you can set setClickable(false) and once the service responds you will do setClicklable(true) through a reference you pass to your custom dialog. When dialog invokes isShowing() you can trigger the listener and setClicklable(true).
如果你不想(或不能)使用布尔标志或覆盖onClickListener,你也可以尝试用android:launchMode="singleTop"在AndroidManifest.xml声明你的活动。
它是如何工作的?
如果活动的实例位于堆栈顶部- new activity不会被创建,相反- onNewIntent()将被调用。 活动可以有多个实例 实例可以驻留在不同的任务中 一个任务可以有多个实例
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图
- 文件google-services错误。模块根文件夹中缺少Json。谷歌服务插件没有它就不能正常工作。