OnTextChangedListener on programaticaly added edit text does not work
correctly
I have created a Edit text programatically and added a text watcher to it,
my code is shown below:
txtPrice = new EditText(this);
txtPrice.setHint("Price");
txtPrice.setTextColor(Color.GRAY);
txtPrice.setGravity(Gravity.CENTER_VERTICAL);
txtPrice.setTextSize(20);
txtPrice.setPadding(20, 0, 0, 0);
txtPrice.setBackgroundColor(Color.WHITE);
txtPrice.addTextChangedListener(new NumberTextWatcher(txtPrice));
txtPrice.setFilters(new InputFilter[] { new InputFilter.LengthFilter(9) });
txtPrice.setInput
Type(InputType.TYPE_CLASS_NUMBER);
This class adds a comma to any number added eg: 1,356,785 when I add it to
an edit text that is defined normally:
@Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v =
s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()),
"");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelection(sel);
} else {
// place cursor at the end?
et.setSelection(et.getText().length() - 1);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
At the moment it only adds a blank space. Does anyone have any help or
suggestions for me? I do not understand why this does not want to work.
Thank you in advance
No comments:
Post a Comment