اون کد رو خیلی سریع نوشتم و تست نکرده بودم. این یکی تست شده. البته بجای getText باید از getPlainText استفاده کنید:
public class Digit3EditText extends AppCompatEditText {
public Digit3EditText(Context context) {
super(context);
init();
}
public Digit3EditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public Digit3EditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
if (!isInEditMode()) {
setText("0 تومان");
setSelection(getText().toString().length());
setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
backSpace();
} else {
DecimalFormat formatter = new DecimalFormat("#");
formatter.setGroupingUsed(true);
formatter.setGroupingSize(3);
String s = getText().toString().replaceAll("[^0-9]", "");
switch (keyCode) {
case KeyEvent.KEYCODE_0:
s += "0";
break;
case KeyEvent.KEYCODE_1:
s += "1";
break;
case KeyEvent.KEYCODE_2:
s += "2";
break;
case KeyEvent.KEYCODE_3:
s += "3";
break;
case KeyEvent.KEYCODE_4:
s += "4";
break;
case KeyEvent.KEYCODE_5:
s += "5";
break;
case KeyEvent.KEYCODE_6:
s += "6";
break;
case KeyEvent.KEYCODE_7:
s += "7";
break;
case KeyEvent.KEYCODE_8:
s += "8";
break;
case KeyEvent.KEYCODE_9:
s += "9";
break;
}
if (s.length() > 0) {
try {
s = formatter.format(Long.parseLong(s)) + " تومان";
} catch (NumberFormatException e) {
s = formatter.format(Long.parseLong(s.substring(0, s.length() - 1))) + " تومان";
}
} else {
s = "0 تومان";
}
setText(s);
setSelection(s.length());
}
}
return true;
}
});
addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (after == 0) {
removeTextChangedListener(this);
backSpace();
addTextChangedListener(this);
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}
}
public String getPlainText() {
return getText().toString().replaceAll("[^0-9]", "");
}
public void backSpace() {
DecimalFormat formatter = new DecimalFormat("#");
formatter.setGroupingUsed(true);
formatter.setGroupingSize(3);
String s = getText().toString().replaceAll("[^0-9]", "");
s = s.length() > 0 ? s.substring(0, s.length() - 1) : "0";
if (s.length() > 0) {
try {
s = formatter.format(Long.parseLong(s)) + " تومان";
} catch (NumberFormatException e) {
s = formatter.format(Long.parseLong(s.substring(0, s.length() - 1))) + " تومان";
}
} else {
s = "0 تومان";
}
setText(s);
setSelection(s.length());
}
}