8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android ボタンの短押し対策について

Last updated at Posted at 2019-04-25

はじめに

Androidアプリでよくあるやつです。

OnClickListenerを設定したViewを、もの凄い勢いで連打した場合、
高確率で複数クリックイベントが発行されてしまいます。

Activityが多重に重なったり、通信処理が複数走ったりと、バグの要因になりえます。

今回、ボタンの短押し対策をKotlinの拡張関数で実装してみました。

対策前

ボタン連打で多重に画面が起動する。

pre.gif

対策コード

拡張関数で以下を定義します。

画面に複数コントロールを配置していても、
clickTime が 1000ms 満たしていないと、クリック不可となります。

ViewExtension.kt
import android.view.View

private var clickTime: Long = 0

fun <T : View> T.setOnSafeClickListener(block: (T) -> Unit) {
    this.setOnClickListener { view ->
        if (System.currentTimeMillis() - clickTime < 1000) {
            return@setOnClickListener
        }
        @Suppress("UNCHECKED_CAST")
        block(view as T)
        clickTime = System.currentTimeMillis()
    }
}

呼び出し元はこんな感じです。

view.setOnSafeClickListener {
    // ...
}

対策後

post.gif

画面をブロッキング(プログレス表示)しない場合は、
isEnabled や isClickable をよになに無効にすればいいかと思います。

hogeButtion.setOnSafeClickListener { button ->
    button.isEnabled = false
    // ...

以上。

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?