Reputation: 280
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:inputType="numberDecimal"
android:digits="0123456789,"
android:gravity="center"/>
After Defining digits it allow me to use "," but only problem I am facing that, I can enter "," multiple time. I want to restrict user so that he can input only one Decimal separator that is comma "," in my case.
Upvotes: 1
Views: 199
Reputation: 280
boolean hasComma = false;
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (hasComma && (source.equals(".") || source.equals(",")))
{
return "";
}
return source;
}
};
// set input filter for edit text
editText.setFilters(new InputFilter[]{filter});
editText.addTextChangedListener(new TextWatcher() {
@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(!hasComma && s.toString().contains("."))
{
s= replaceComma(s.toString());
editText.setText(s);
editText.setSelection(start + 1);
hasComma =true;
}
}
@Override
public void afterTextChanged(Editable s) {
if (s.toString().contains(",") || s.toString().contains("."))
{
hasComma =true;
}
else {
hasComma = false;
}
}
});
//use this method to replace "." to ","
private CharSequence replaceComma(String s) {
return s.replace('.',',');
}
Upvotes: 0