上記は一度クリックされたら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()
}
}
}