说明:
android中要求输入框中只能输入有符号数字,并且限制范围,下面给出要求,例子和函数
有需要可以借鉴。
要求:
- 输入整数数字,范围-180~180。
- 首字符一定是非零数字或-
- 中间不能有-
代码:
界面
<EditText
android:id="@+id/et_item_left"
android:layout_width="10dp"
android:layout_height="match_parent"
android:layout_marginBottom="@dimen/dp_1"
android:layout_weight="1"
android:background="#ffffff"
android:digits="-0123456789"
android:gravity="center"
android:imeOptions="actionNext"
android:inputType="numberSigned"
android:maxLength="4"
android:maxLines="1"
android:text="-100"
android:textColor="#333333"
android:textSize="@dimen/sp_13"
tools:maxLength="10"
tools:text="数字限制例子" />
用法
EditText etItemRight = itemView.findViewById(R.id.et_item_right);
EtLimit(etItemLeft, -180, 180,(editable)->{info.setLeft(Text2Int(editable.toString()));});
函数
public static void EtLimit(EditText et, int maxValue) {
EtLimit(et, 0, maxValue, null);
}
public static void EtLimit(EditText et, int minValue, int maxValue) {
EtLimit(et, minValue, maxValue, null);
}
public static void EtLimit(EditText et, int maxValue, TextViewBindingAdapter.AfterTextChanged textChanged) {
EtLimit(et, 0, maxValue, textChanged);
}
public static void EtLimit(EditText et, int minValue, int maxValue, TextViewBindingAdapter.AfterTextChanged textChanged) {
et.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void afterTextChanged(Editable arg0) {
String content = arg0.toString();
if (content.length() > 0) {
if (content.length() == 1 && content.startsWith("-")) {
return;
}
if (content.length() > 1 && content.startsWith("0")) {
arg0.replace(0, 1, "");
return;
}
if (content.length() > 2 && content.startsWith("-0")) {
arg0.replace(1, 2, "");
return;
}
Integer num;
try {
num = Integer.parseInt(content);
} catch (NumberFormatException e) {
content = content.substring(1).replace("-", "");
Editable ab = new SpannableStringBuilder(content);
arg0.replace(1, arg0.length(), ab);
return;
}
if (num > maxValue || num < minValue) {
if (content.length() >= 1) {
arg0.delete(content.length() - 1, content.length());
}
} else {
if (textChanged != null) {
textChanged.afterTextChanged(arg0);
}
}
}
}
});
}
关于: