Reputation: 138
I´m adding a Thousands separator on my TextWatcher
Code:
override fun afterTextChanged(s: Editable) {
var initial = s.toString()
if (!TextUtils.isEmpty(initial)) {
initial = initial.replace(".", "")
val formatSymbols = DecimalFormatSymbols()
formatSymbols.groupingSeparator = '.'
val formatter: NumberFormat = DecimalFormat("###,###,###", formatSymbols)
editText.removeTextChangedListener(this)
val myNumber = initial.toDouble()
val processed: String = formatter.format(myNumber)
s.clear()
s.append(processed)
editText.addTextChangedListener(this)
}
}
For testing, I input the number 1000, and it works fine. It outputs 1.000 Input 100000 and works fine again, output is 100.000 For some reason, when I input 1000000, the processed variable is 1.000.000, but when I append to the Editable, it appends as 1000.000
Image showing the variable Processed is correct, but the appended result isn´t
Any ideas as to why it´s happening?
I could set the text of the edittext directly, but that´s not my goal right now
Upvotes: 0
Views: 116
Reputation: 138
Okey so the code was indeed working correctly. Apparently the issue was the InputType I was using for the keyboard, which was:
InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL
Totally my bad
No idea how to make the keyboard so it shows just numbers, yet make it work with the filter i´m using, but that´s atleast an issue I can work on
Thanks everyone for the help!
Upvotes: 1
Reputation: 518
I've tested you code and it seems to work fine.
You can try to add it to your tests and experiment with that
Editable
is a SpannableStringBuilder
, and to instantiate it you have to use RoboeletricTestRunner
dependencies {
testImplementation 'org.robolectric:robolectric:4.4'
}
@RunWith(RobolectricTestRunner.class)
public class MyTests {
fun afterTextChanged(editable: Editable) { ... }
@Test
fun testAfterTextChanged() {
afterTextChanged(SpannableStringBuilder("1000000"))
}
}
Upvotes: 1