您的位置:首页 > 其它

Edittext 限制只能输入数字和字母

2015-05-25 10:58 471 查看
项目里的注册页面需要对Edittext做出只能输入数字和字母的限制,同时也可以支持明文和密文显示,方法如下:

1. 控件里面先限制显示数字和字母,为了是在明文和密文切换的时候也保持一致

<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_toLeftOf="@+id/iv_password"
android:background="@null"
android:digits="0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
android:hint="@string/label_password_tip"
android:inputType="textPassword"
android:maxLength="16"
android:minEms="6"
android:singleLine="true"
android:textSize="15sp" />

2.给控件添加监听
// 显示密文
iv_password_visible.setVisibility(View.GONE);
iv_password.setVisibility(View.VISIBLE);
et_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
et_password.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void afterTextChanged(Editable edt) {
try {
String temp = edt.toString();
String tem = temp.substring(temp.length() - 1, temp.length());
char[] temC = tem.toCharArray();
int mid = temC[0];
if (mid >= 48 && mid <= 57) {// 数字
return;
}
if (mid >= 65 && mid <= 90) {// 大写字母
return;
}
if (mid > 97 && mid <= 122) {// 小写字母
return;
}
edt.delete(temp.length() - 1, temp.length());
} catch (Exception e) {
// TODO: handle exception
}
}
});
setCursorLocation();
// 显示明文
iv_password.setVisibility(View.GONE);
iv_password_visible.setVisibility(View.VISIBLE);
et_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
et_password.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void afterTextChanged(Editable edt) {
try {
String temp = edt.toString();
String tem = temp.substring(temp.length() - 1, temp.length());
char[] temC = tem.toCharArray();
int mid = temC[0];
if (mid >= 48 && mid <= 57) {// 数字
return;
}
if (mid >= 65 && mid <= 90) {// 大写字母
return;
}
if (mid > 97 && mid <= 122) {// 小写字母
return;
}
edt.delete(temp.length() - 1, temp.length());
} catch (Exception e) {
// TODO: handle exception
}
}
});
setCursorLocation();


点击事件切换明文密文
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: