在安卓系统中防止双击按钮的最佳方法是什么?
当前回答
I found none of these suggestions works if the onClick method doesn't return immediately. The touch event is queued by Android and the next onClick is called only after the first one is finished. (Since this is done on the one UI thread this is really normal.) I needed to use the time when the the onClick function is finished + one boolean variable to mark whether the given onClick is running. Both these marker attributes are static to avoid any onClickListener to run at the same time. (If user clicks on another button) You can simple replace your OnClickListener to this class and instead of implementing the onClick method you need to implement the abstract oneClick() method.
abstract public class OneClickListener implements OnClickListener {
private static boolean started = false;
private static long lastClickEndTime = 0;
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
final public void onClick(final View v) {
if(started || SystemClock.elapsedRealtime()-lastClickEndTime <1000 ){
Log.d(OneClickListener.class.toString(), "Rejected double click, " + new Date().toString() );
return;
}
Log.d(OneClickListener.class.toString(), "One click, start: " + new Date().toString() );
try{
started = true;
oneClick(v);
}finally{
started = false;
lastClickEndTime = SystemClock.elapsedRealtime();
Log.d(OneClickListener.class.toString(), "One click, end: " + new Date().toString() );
}
}
abstract protected void oneClick(View v);
}
其他回答
使用setEnabled(false)禁用按钮,直到用户可以安全地再次单击它。
具有Kotlin扩展功能:
fun View.onSingleClick(action: (v: View) -> Unit) {
setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View) {
isClickable = false
action(v)
postDelayed({ isClickable = true }, 700)
}
})
}
用法:
button.onSingleClick { myAction() }
通用解决方案
@Override
public void onClick(View v) {
tempDisableButton(v);
//all the buttons view..
}
public void tempDisableButton(View viewBtn) {
final View button = viewBtn;
button.setEnabled(false);
button.postDelayed(new Runnable() {
@Override
public void run() {
button.setEnabled(true);
}
}, 3000);
}
似乎设置你的点击监听器在onResume和空他们在onPause也有技巧。
你可以使用这种方法。通过使用后延迟,你可以照顾双击事件。
void debounceEffectForClick(查看视图){
view.setClickable(false);
view.postDelayed(new Runnable() {
@Override
public void run() {
view.setClickable(true);
}
}, 500);
}
推荐文章
- 警告:API ' variable . getjavacompile()'已过时,已被' variable . getjavacompileprovider()'取代
- 安装APK时出现错误
- 碎片中的onCreateOptionsMenu
- TextView粗体通过XML文件?
- 如何使线性布局的孩子之间的空间?
- DSL元素android.dataBinding。enabled'已过时,已被'android.buildFeatures.dataBinding'取代
- ConstraintLayout:以编程方式更改约束
- PANIC: AVD系统路径损坏。检查ANDROID_SDK_ROOT值
- 如何生成字符串类型的buildConfigField
- Recyclerview不调用onCreateViewHolder
- Android API 21工具栏填充
- Android L中不支持操作栏导航模式
- 如何在TextView中添加一个子弹符号?
- PreferenceManager getDefaultSharedPreferences在Android Q中已弃用
- 在Android Studio中创建aar文件