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


当前回答

防止点击乘法btns

使用:

private val disposables = CompositeDisposable()
private val clickInteractor = ClickInteractor(disposables)
...
button1.setOnClickListener{
     clickInteractor.click {
          Toast.makeText(context, "Btn1", Toast.LENGTH_LONG).show()
     }
}
button2.setOnClickListener{
     clickInteractor.click {
          Toast.makeText(context, "Btn2", Toast.LENGTH_LONG).show()
     }
}

ClickInteractor.kt:

class ClickInteractor constructor(disposables: CompositeDisposable) {
    private val performPublish = PublishSubject.create<ClickInteractorCallback>()

    init {
        performPublish
            .subscribeOn(Schedulers.io())
            .observeOn(Schedulers.io())
            .throttleFirst(1, TimeUnit.SECONDS, Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext { callback ->
                callback.invoke()
            }
            .retry()
            .execute(disposables)
    }

    fun click(callback: ClickInteractorCallback) {
        performPublish.onNext(callback)
    }
}

typealias ClickInteractorCallback = () -> Unit

其他回答

下面是kotlin扩展函数的方式,将工作于所有视图,保持以下函数在您的Utils或任何文件

fun View.preventDoubleClick() {
this.isEnabled = false
this.postDelayed( { this.isEnabled = true }, 1000)
}

下面是如何从片段或活动中使用它

anyIdOfView?.setOnClickListener {
it.preventDoubleClick()
YourAction()
}

这个问题的实际解决方案是使用setEnabled(false),灰色按钮,和setClickable(false),使它第二次点击不能接收,我已经测试过了,它似乎是非常有效的。

您也可以使用jake Wharton的rx绑定来实现这一点。下面是一个连续点击之间间隔2秒的例子:

RxView.clicks(btnSave)
                .throttleFirst(2000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept( Object v) throws Exception {
//handle onclick event here
                });

//注意:忽略对象v在这种情况下,我认为总是。

KLEANEST Kotlin惯用方式:

class OnSingleClickListener(private val block: () -> Unit) : View.OnClickListener {

    private var lastClickTime = 0L

    override fun onClick(view: View) {
        if (SystemClock.elapsedRealtime() - lastClickTime < 1000) {
            return
        }
        lastClickTime = SystemClock.elapsedRealtime()

        block()
    }
}

fun View.setOnSingleClickListener(block: () -> Unit) {
    setOnClickListener(OnSingleClickListener(block))
}

用法:

button.setOnSingleClickListener { ... }

或者加上一个控制油门的附加参数

class OnClickListenerThrottled(private val block: () -> Unit, private val wait: Long) : View.OnClickListener {

    private var lastClickTime = 0L

    override fun onClick(view: View) {
        if (SystemClock.elapsedRealtime() - lastClickTime < wait) {
            return
        }
        lastClickTime = SystemClock.elapsedRealtime()

        block()
    }
}

/**
 * A throttled click listener that only invokes [block] at most once per every [wait] milliseconds.
 */
fun View.setOnClickListenerThrottled(wait: Long = 1000L, block: () -> Unit) {
    setOnClickListener(OnClickListenerThrottled(block, wait))
}

Usages:

button.setOnClickListenerThrottled(2000L) { /** some action */}
or
button.setOnClickListenerThrottled { /** some action */}

如果你在onClick()中进行计算密集型工作,则禁用按钮或设置不可点击是不够的,因为单击事件可以在禁用按钮之前排队。我写了一个实现OnClickListener的抽象基类,你可以重写,通过忽略任何排队点击来修复这个问题:

/** 
 * This class allows a single click and prevents multiple clicks on
 * the same button in rapid succession. Setting unclickable is not enough
 * because click events may still be queued up.
 * 
 * Override onOneClick() to handle single clicks. Call reset() when you want to
 * accept another click.
 */
public abstract class OnOneOffClickListener implements OnClickListener {
    private boolean clickable = true;

    /**
     * Override onOneClick() instead.
     */
    @Override
    public final void onClick(View v) {
        if (clickable) {
            clickable = false;
            onOneClick(v);
            //reset(); // uncomment this line to reset automatically
        }
    }

    /**
     * Override this function to handle clicks.
     * reset() must be called after each click for this function to be called
     * again.
     * @param v
     */
    public abstract void onOneClick(View v);

    /**
     * Allows another click.
     */
    public void reset() {
        clickable = true;
    }
}

用法与OnClickListener相同,但重写OnOneClick()代替:

OnOneOffClickListener clickListener = new OnOneOffClickListener() {
    @Override
    public void onOneClick(View v) {

        // Do stuff

        this.reset(); // or you can reset somewhere else with clickListener.reset();
    }
};
myButton.setOnClickListener(clickListener);