I am working on app where an edittext is having $0 as pre-defined text. Zero is editable. But as soon as user enters an amount like $80, its showing $080. I am using textwatcher to non deleted $ and replaced at time of printing value.
How can i achieve the output as $80 when user is typing an amount
preset value - $0 after typing $80, Output = $080 Expected = $80
Thanks in advance.
amountEdittext.setText("$0");
Selection.setSelection(amountEdittext.getText(),
amountEdittext.getText().length());
amountEdittext.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
if (!s.toString().startsWith("$")) {
amountEdittext.setText("$");
Selection.setSelection(amountEdittext.getText(), amountEdittext.getText().length());
}
}
});
This should solve your question.
amountEdittext.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (editable.length() > 2) {
for (int i = 0; i < editable.length() - 1; i++) {
if (editable.charAt(i) == '$' && editable.charAt(i + 1) == '0') {
editable.delete(i + 1, i + 2);
}
}
}
}
});
}