项目中,规定输入框要有一些限制,比如
0-》 0.
00078-》78
0.12323-》0.12
- edit.xml
选择输入类型 android:inputType=”numberDecimal”
<EditText
android:id="@+id/withdrawal_bunding_edt_withdrawal_money"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:singleLine="true"
android:textColor="@color/common_color_666666"
android:focusableInTouchMode="true"
android:textCursorDrawable="@drawable/color_cursor"
android:textSize="14.0sp" />
- MainActivity.java
TextWatcher withdrawalWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String zero = Constants.VAR_ZERO; //0
String dot = Constants.HIDDEN_PREFIX; //.
String cash = s.toString();
int length = cash.length();
if (cash.startsWith(dot)) {
if (length > 3) {
cash = cash.substring(0, 3);
}
cash = zero + cash;
edtWithdrawal.setText(cash);
edtWithdrawal.setSelection(cash.length());
} else if (cash.contains(dot)) {
if (cash.startsWith(zero) && length > 1 && !cash.substring(1, 2).equals(dot)) {
if (!cash.substring(1, 2).equals(zero)) {
String subString = cash.substring(1, length);
edtWithdrawal.setText(subString);
edtWithdrawal.setSelection(subString.length());
}
}
if ((length - 1) - cash.indexOf(dot) > 2) {
cash = cash.substring(0, cash.indexOf(dot) + 3);
edtWithdrawal.setText(cash);
edtWithdrawal.setSelection(cash.length());
}
} else if (cash.startsWith(zero) && length > 1 && !cash.substring(1, 2).equals(dot)) {
if (!cash.substring(1, 2).equals(zero)) {
String subString = cash.substring(1, length);
edtWithdrawal.setText(subString);
edtWithdrawal.setSelection(subString.length());
}
}
if (!TextUtils.isEmpty(cash)) {
if (Double.parseDouble(cash) > mCashTotal) {
edtWithdrawal.setText(mLastInput);
edtWithdrawal.setSelection(start);
}
} else {
mLastInput = null;
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
String cash = s.toString();
}
};
大概思路:
if (cash.startsWith(dot)) {
if (length > 3) { //防止用户删除,输入. 例:123→前面输入. 。 这个时候就 .123跟下一个判断有冲突
cash = cash.substring(0, 3);
}
cash = zero + cash;
edtWithdrawal.setText(cash);
edtWithdrawal.setSelection(cash.length());
}
if (cash.startsWith(zero) && length > 1 && !cash.substring(1, 2).equals(dot)) { //优化开头输入 00123(光标移到头部可以输入00)
if (!cash.substring(1, 2).equals(zero)) {
String subString = cash.substring(1, length);
edtWithdrawal.setText(subString);
edtWithdrawal.setSelection(subString.length());
}
}
一开始就优化输入 0123 - 》 123
if (cash.startsWith(zero) && length > 1 && !cash.substring(1, 2).equals(dot)) {
if (!cash.substring(1, 2).equals(zero)) {
String subString = cash.substring(1, length);
edtWithdrawal.setText(subString);
edtWithdrawal.setSelection(subString.length());
}
}