I need to create a custom numeric keyboard in Android Studio using Kotlin. I successfully implemented the view with keyboard buttons (from 0 to 9 and one delete button) and TextInputEditText that shows the result. I implemented also the buttons in my fragment:
result = binding.editTextInsert
// Data input buttons
val button0: AppCompatButton = binding.button0
...
val buttonDelete: ImageButton = binding.buttonDelete
val listener = View.OnClickListener { v ->
val b = v as AppCompatButton
result.append(b.text)
}
button0.setOnClickListener(listener)
...
But I want to auto format the TextInputEditText in a decimal format 0.00:
if a user press 1 it becomes 0.01 instead of 1
if he entered 100, then the value in the TextInputEditText must be formatted as 1.00.
I assume this can be done by using TextWatcher and loop but I don't know how to achieve this.
EDIT Correct answer based from here
binding.editTextInsert.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(s: Editable?) {
var current: String = ""
if (s.toString() != current) {
result.removeTextChangedListener(this)
val cleanString: String = s!!.replace("""[$,.]""".toRegex(), "")
val parsed: BigDecimal =
BigDecimal(cleanString).setScale(2, BigDecimal.ROUND_FLOOR)
.divide(BigDecimal(100), BigDecimal.ROUND_FLOOR)
val formatted: String = NumberFormat.getCurrencyInstance().format(parsed)
current = parsed.toString()
result.setText(parsed.toString())
result.setSelection(parsed.toString().length)
result.addTextChangedListener(this)
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { }
})