您的位置:首页 > 移动开发 > Android开发

Android EditView 输入限制(软键盘限制)

2016-06-25 19:14 330 查看
众所周知EditView有个inputType 属性可以设置输入的类型。

如下设置,则只能输入数字:

android:inputType="number"


但是有时候需要自定义输入限制条件,比如第一位只能是“1”,一共11位,超过11位则无法输入,或者只允许输入小于5以下的数字等,则需要其他设置。Android中有三种方式来设置。

第一种:digits 属性

如下设置为:只能输入0-5之间的数字,且最多11位。

<EditText
android:id="@+id/etDigits"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="012345"
android:hint="通过digits设置"
android:inputType="number"
android:maxLength="11" />


PS:优点:简单方便;

缺点:只能设置简单的限制,如果需要设置的比较复杂,如数字字母和某些特定字符则需要在digits中穷举出来。

第二种:TextWatcher设置

此方式也比较灵活,不错的方式。

EditText etTextWatcher = (EditText) findViewById(R.id.etTextWatcher);
etTextWatcher.addTextChangedListener(new EditTextWatcher(etTextWatcher));
/**
* Created by xugang on 2016/6/23.
* 输入监听
*/
public class EditTextWatcher implements TextWatcher {
private EditText editText;
public EditTextWatcher(EditText editText) {
this.editText = editText;
}
@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 (s != null && s.length() > start) {
//输入判断规则
if (!RegularUtils.compare(s.toString().trim(), RegularUtils.LIMIT_PHONE_INPUT)) {
editText.setText(s.subSequence(0, s.length() - 1));
editText.setSelection(s.length() - 1);
}
}
}
@Override
public void afterTextChanged(Editable s) {
}
}


第三种:设置Filters,通过正则进行限制

传入正则规则即可,灵活性比较高。

public static final String LIMIT_PHONE_INPUT = "^1\\d{0,10}$";//限制只允许输入首位为1的最多11位的数字
EditView etInputFilter = (EditView)findViewById(R.id.etInputFilter);
etInputFilter.setFilters(new EditInputFilter(LIMIT_PHONE_INPUT));
/**
* Created by xugang on 2016/6/22.
* EditView过滤器
*/
public class EditInputFilter implements InputFilter {
//
private String regular;
public EditInputFilter(String regular) {
this.regular = regular;
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (regular == null)
return source;
if (dstart == 0 && dend == 0 && TextUtils.isEmpty(source))
return null;
if (dstart == dend) {
//输入
StringBuilder builder = new StringBuilder(dest);
if (builder.append(source).toString().matches(regular)) return source;
else return "";
}
return source;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android