When entering numbers in EditText, we usually need to limit the number of digits before and after the decimal point. For example, when entering the amount, we generally need to limit the maximum of 2 digits after the decimal point. We can implement it through TextWatcher.
public class MyWatcher implements TextWatcher { private int beforeDot; private int afterDot; /** * Constructor * * @param beforeDot Number of decimal places without limit input -1 * @param afterDot Number of decimal places without limiting input -1 */ public MyWatcher(int beforeDot, int afterDot) { = beforeDot; = afterDot; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { judge(s); } private void judge(Editable editable) { String temp = (); int posDot = ("."); //State of directly entering the decimal point if (posDot == 0) { (0, "0"); return; } //Continuous input 0 if (("00")) { (1, 2); return; } //Enter "08" and other similar situations if (("0") && () > 1 && (posDot == -1 || posDot > 1)) { (0, 1); return; } //No decimal points are included. No limit on the number of predecimal points. if (posDot < 0 && beforeDot == -1) { //do nothing just to understand logic return; } else if (posDot < 0 && beforeDot != -1) { //No decimal points are included. Limit the number of decimal points before the decimal points if (() <= beforeDot) { //do nothing just to understand logic } else { (beforeDot, beforeDot + 1); } return; } //If you include decimal points, limit the number of decimal points after the decimal points if (() - posDot - 1 > afterDot && afterDot != -1) { (posDot + afterDot + 1, posDot + afterDot + 2);//Delete the number of extra digits after the decimal point } } }
When using it, the following is:
<EditText android: android:layout_width="wrap_content" android:layout_height="25dp" android:hint="0.00" android:inputType="numberDecimal"/>(new MyWatcher(-1, 2));//Limit the maximum number of decimal points2Bit
The above example of EditText limiting the number of digits before and after the decimal point is all the content I share with you. I hope you can give you a reference and I hope you can support me more.