押しっぱなしでテキストボックス数字の値を変化させるボタンを作成するためのクラスを作成しました。使い方は以下を参照してください。ウェジットは適宜調整してください。
// kotlin code 使い方
//要素を取得する
val dec=findViewById<AppCompatButton>(R.id.Decrease)
val inc=findViewById<AppCompatButton>(R.id.Increase)
val text=findViewById<AppCompatEditText>(R.id.editTextPrice)
//加減算用にそれぞれクラスを初期化
ValueChangeButtonHandler(inc,text,true)
ValueChangeButtonHandler(dec,text,false)
// kotlin code ValueChangeButtonHandlerクラスの実装
import android.os.Handler
import android.text.Editable
import android.text.TextWatcher
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.AppCompatEditText
class ValueChangeButtonHandler(private val button: AppCompatButton, private val editText: AppCompatEditText, private val increase: Boolean) {
private var valueChangeTimer: Handler? = null
init {
button.setOnTouchListener { view, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
startValueChangeTimer()
true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
stopValueChangeTimer()
true
}
else -> false
}
}
editText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
try {
val currentValue = s.toString().toDouble()
// 値の取得に成功した場合の処理
} catch (e: NumberFormatException) {
// 値の取得に失敗した場合の処理
editText.error = "Invalid value"
}
}
})
}
private fun startValueChangeTimer() {
valueChangeTimer = Handler()
valueChangeTimer?.postDelayed(object : Runnable {
override fun run() {
changeValue()
valueChangeTimer?.postDelayed(this, 100) // 100ミリ秒ごとに処理を実行
}
}, 0)
}
private fun stopValueChangeTimer() {
valueChangeTimer?.removeCallbacksAndMessages(null)
valueChangeTimer = null
}
private fun changeValue() {
try {
val currentValue = editText.text.toString().toDouble()
// 加減算する値を指定する
val changeValue=0.01
val newValue = if (increase) currentValue + changeValue else currentValue - changeValue
editText.setText(String.format("%.2f", newValue))
} catch (e: NumberFormatException) {
// 値の取得に失敗した場合の処理
editText.error = "Invalid value"
}
}
}
コメント