Попробуйте, я создал собственное представление для ввода валюты. Используйте метод currency()
для получения значения в EditText.
class CurrencyInput(context: Context, attributeSet: AttributeSet) : TextInputEditText(context, attributeSet) {
private val currencyTextWatcher = CurrencyWatcher()
override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
super.onFocusChanged(focused, direction, previouslyFocusedRect)
if (focused) addTextChangedListener(currencyTextWatcher) else removeTextChangedListener(currencyTextWatcher)
}
fun currency(): Long = currencyTextWatcher.amount
private fun Long.toDecimalStr(): String = decimalFormatter().format(this)
inner class CurrencyWatcher : TextWatcher {
var amount = 0L
var amountDecimal = ""
override fun afterTextChanged(editable: Editable?) {
editable?.toString()?.run {
when {
equals("") -> {
amount = 0
amountDecimal = "0"
}
else -> {
amount = replace(",", "").replace(".", "").toLong()
amountDecimal = if (amount >= 1000) amount.toDecimalStr() else amount.toString()
}
}
this@CurrencyInput.apply {
removeTextChangedListener(this@CurrencyWatcher)
amount.let {
setText(amountDecimal)
setSelection(amountDecimal.length)
}
addTextChangedListener(this@CurrencyWatcher)
}
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { }
}
}
Замените на имя вашего пакета при использовании CurrencyInput в макете
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="7dp"
android:hint="Currency"
app:endIconMode="clear_text">
<com.package.CurrencyInput
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"/>
</com.google.android.material.textfield.TextInputLayout>