LoginSignup
0
2

More than 3 years have passed since last update.

コピペでできるボタン連打防止(android)

Posted at

disable_repeat.gif

上記は一度クリックされたら2000msだけクリックを禁止しています。
isEnabled = falseにしたりtrueにしたり、あまり綺麗ではないので拡張しました。

Button.kt

import android.os.Handler
import android.widget.Button


fun Button.disableClick(milliSec: Int) {
    // clickの制御
    if (!this.isEnabled) {
        return
    }
    this.isEnabled = false
    Handler().postDelayed( {
        this.isEnabled = true
    }, milliSec.toLong())
}

…これだけですw

使い方は

MainActivity.kt

class MainActivity: AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setStopRepeatButton()
    }

    private fun setStopRepeatButton() {
        // countの初期値を0にします
        button.text = "0"

        // ここで設定しています
        //(単位を明らかにするために書きましたが
        //milliSecは省略できます)
        button.setOnClickListener {
            button.disableClick(milliSec = 2000)

            val count = Integer.parseInt(button.text.toString())
            button.text = (count + 1).toString()
        }
    }
}

0
2
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
0
2