How to use EditText onTextChanged event when I press the number?
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();
}
});
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.
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;
}
}
});
put the logic in
afterTextChanged(Editable s) {
string str = s.toString()
// use the string str
}
documentation on TextWatcher