在安卓系统中防止双击按钮的最佳方法是什么?


当前回答

我也遇到了类似的问题,我正在显示一些日期选择器和时间选择器,有时它会被点击2次。我用这个方法解决了这个问题:

long TIME = 1 * 1000;
@Override
public void onClick(final View v) {
v.setEnabled(false);
    
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            v.setEnabled(true);
        }
    }, TIME);
}

你可以根据自己的需要改变时间。

其他回答

setEnabled(false)非常适合我。

我写{setEnabled(true);},并在第一次点击按钮时将其设为false。

我知道这是一个老问题,但我分享了我找到的解决这个常见问题的最佳方案

        btnSomeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Prevent Two Click
            Utils.preventTwoClick(view);
            // Do magic
        }
    });

在另一个文件中,比如Utils.java

    /**
 * Método para prevenir doble click en un elemento
 * @param view
 */
public static void preventTwoClick(final View view){
    view.setEnabled(false);
    view.postDelayed(
        ()-> view.setEnabled(true),
        500
    );
}

使用setEnabled(false)禁用按钮,直到用户可以安全地再次单击它。

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).

在Java中有一个本地debounce click监听器

view.setOnClickListener(new DebouncedOnClickListener(1000) { //in milisecs
            @Override
            public void onDebouncedClick(View v) {
                //action
            }
        });