在安卓系统中防止双击按钮的最佳方法是什么?
当前回答
如果有人还在寻找一个简短的答案,你可以使用下面的代码
private static long mLastClickTime = 0;
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) { // 1000 = 1second
return;
}
mLastClickTime = SystemClock.elapsedRealtime();
当用户在1秒内单击View时,这段代码将进入if语句,然后返回;将被启动,而进一步的代码将不会被启动。
其他回答
如果有人还在寻找一个简短的答案,你可以使用下面的代码
private static long mLastClickTime = 0;
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) { // 1000 = 1second
return;
}
mLastClickTime = SystemClock.elapsedRealtime();
当用户在1秒内单击View时,这段代码将进入if语句,然后返回;将被启动,而进一步的代码将不会被启动。
加上Jim的回答,代码可以变得更简洁:
fun View.setOnSingleClick(onClick: () -> Unit) {
var lastClickTime = 0L
setOnClickListener {
if (currentTimeMillis() > lastClickTime + 750) onClick()
lastClickTime = currentTimeMillis()
}
}
用法:
aView.setOnSingleClick { }
我希望这能帮助你,把代码放在你的事件处理程序。
// --------------------------------------------------------------------------------
boolean hasTag = null != which.getTag( R.id.preventing_double_click_tag );
if ( hasTag ) {
// Do not handle again...
return;
} else {
which.setTag( R.id.action, Boolean.TRUE );
which.postDelayed( new Runnable() {
@Override
public void run() {
which.setTag( R.id.action, null );
Log.d( "onActin", " The preventing double click tag was removed." );
}
}, 2000 );
}
在Java中有一个本地debounce click监听器
view.setOnClickListener(new DebouncedOnClickListener(1000) { //in milisecs
@Override
public void onDebouncedClick(View v) {
//action
}
});
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).
推荐文章
- 视图绑定-我如何获得包含布局的绑定?
- 在Android Studio中改变矢量资产的填充颜色
- 在构建中编写注释的语法是什么?gradle文件?
- 如何以编程方式添加按钮色调
- 用Android Studio进行调试永远停留在“等待调试器”状态
- Openssl不被视为内部或外部命令
- 无法执行dex:在Eclipse中超过GC开销限制
- 如何以编程方式将视图添加到视图
- 单击url会打开默认浏览器
- 使用Retrofit刷新OAuth令牌,而不修改所有调用
- 多个dex文件定义了landoid /support/v4/accessibilityservice/AccessibilityServiceInfoCompat
- 如何获得动作栏的高度?
- 从活动外部调用startActivity() ?
- createScaledBitmap的过滤器参数做什么?
- 为什么我在使用adb时访问数据文件夹被拒绝?