I have lost an incredible ten hours searching for or trying out codes for this. So I gave up and created this code for myself. This has not yet been revised, but it works, and I came here to help others who were crazy about it, like me.
The code is basically a function that will put the textWatcher and adjust the coma in the right place. This code is for Kotlin.
First create this function:
fun CurrencyWatcher( editText:EditText) {
editText.addTextChangedListener(object : TextWatcher {
var changed: Boolean = false
override fun afterTextChanged(p0: Editable?) {
changed = false
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
editText.setSelection(p0.toString().length)
}
@SuppressLint("SetTextI18n")
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
if (!changed) {
changed = true
var str: String = p0.toString().replace(",", "").trim()
var element0: String = str.elementAt(0).toString()
var element1: String = "x"
var element2: String = "x"
var element3: String = "x"
var element4: String = "x"
var element5: String = "x"
var element6: String = "x"
if (str.length >= 2) {
element1 = str.elementAt(1).toString()
}
if (str.length >= 3) {
element2 = str.elementAt(2).toString()
}
editText.removeTextChangedListener(this)
if (str.length == 1) {
str = "0,0" + str
editText.setText(str)
} else if (str.length <= 3 && str == "00") {
str = "0,00"
editText.setText(str)
editText.setSelection(str.length)
} else if (element0 == "0" && element1 == "0" && element2 == "0") {
str = str.replace("000", "")
str = "0,0" + str
editText.setText(str)
} else if (element0 == "0" && element1 == "0" && element2 != "0") {
str = str.replace("00", "")
str = "0," + str
editText.setText(str)
} else {
if (str.length >= 4) {
element3 = str.elementAt(3).toString()
}
if (str.length >= 5) {
element4 = str.elementAt(4).toString()
}
if (str.length >= 6) {
element5 = str.elementAt(5).toString()
}
if (str.length == 7) {
element6 = str.elementAt(6).toString()
}
if (str.length >= 4 && element0 != "0") {
val sb: StringBuilder = StringBuilder(str)
sb.insert(str.length - 2, ",")
str = sb.toString()
}
if (str.length == 4 && element0 == "0") {
val sb: StringBuilder = StringBuilder(str)
sb.deleteCharAt(0);
str = sb.toString()
val sb2: StringBuilder = StringBuilder(str)
sb2.insert(str.length - 2, ",")
str = sb2.toString()
}
if (str.length == 3 && element0 != "0") {
val sb: StringBuilder = StringBuilder(str)
sb.insert(str.length - 2, ",")
str = sb.toString()
}
if (str.length == 2 && element0 == "0") {
val sb: StringBuilder = StringBuilder(str)
sb.deleteCharAt(0);
str = sb.toString()
str = "0,0" + str
}
if (str.length == 2 && element0 != "0") {
val sb: StringBuilder = StringBuilder(str)
sb.insert(0, "0,")
str = sb.toString()
}
editText.setText(str)
}
editText.setSelection(str.length)
editText.addTextChangedListener(this)
}
}
})
}
And then you call this function this way
val etVal:EditText = findViewById(R.id.etValue)
CurrencyWatcher(etVal)
source
share