How to use EditText onTextChanged event when I press the number?
I have an EditText
with "text = 0.00"
. When I press the number 3, it should be like 0.03
and the second time when I press the number 5, the text should be 0.35
. And 35.0
, 35.09
like this. The EditText
initially has the value of 0.00
.
These are all done with the same EditText
.
How do I achieve this? I have tried using addTextChangedListener()
with TextWatcher()
.
Solution 1:
You can also try this:
EditText searchTo = (EditText)findViewById(R.id.medittext);
searchTo.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
doSomething();
}
});
Solution 2:
You have selected correct approach. You have to extend the class with TextWatcher and override afterTextChanged()
,beforeTextChanged()
, onTextChanged()
.
You have to write your desired logic in afterTextChanged()
method to achieve functionality needed by you.
Solution 3:
Here, I wrote something similar to what u need:
inputBoxNumberEt.setText(". ");
inputBoxNumberEt.setSelection(inputBoxNumberEt.getText().length());
inputBoxNumberEt.addTextChangedListener(new TextWatcher() {
boolean ignoreChange = false;
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (!ignoreChange) {
String string = s.toString();
string = string.replace(".", "");
string = string.replace(" ", "");
if (string.length() == 0)
string = ". ";
else if (string.length() == 1)
string = ". " + string;
else if (string.length() == 2)
string = "." + string;
else if (string.length() > 2)
string = string.substring(0, string.length() - 2) + "." + string.substring(string.length() - 2, string.length());
ignoreChange = true;
inputBoxNumberEt.setText(string);
inputBoxNumberEt.setSelection(inputBoxNumberEt.getText().length());
ignoreChange = false;
}
}
});
Solution 4:
put the logic in
afterTextChanged(Editable s) {
string str = s.toString()
// use the string str
}
documentation on TextWatcher