内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
在我的应用程序中,我必须验证edittext。它
这是我的代码:
edittext.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// validation codes here
location_name=s.toString();
Toast.makeText(getApplicationContext(),location_name, Toast.LENGTH_SHORT).show();
if (location_name.matches(".*[^a-z^0-9].*"))
{
location_name = location_name.replaceAll("[^a-z^0-9]", "");
s.append(location_name);
s.clear();
Toast.makeText(getApplicationContext(),"Only lowercase letters and numbers are allowed!",Toast.LENGTH_SHORT).show();
}
}
});
location.add(location_name);
在这里,当我在edittext中输入输入时,应用程序被强制关闭。
Android中没有使用“手动”检查方法,而是使用了一些非常简单的方法:
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int i = start;i < end;i++) {
if (!Character.isLetterOrDigit(source.charAt(i)) && !Character.toString(source.charAt(i)).equals("_") && !Character.toString(source.charAt(i)).equals("-")) {
return "";
}
}
return null;
}
};
edittext.setFilters(new InputFilter[] { filter });
或者另一种方法:在创建EditText的XML中设置允许的字符:
<EditText
android:inputType="text"
android:digits="0,1,2,3,4,5,6,7,8,9,*,qwertzuiopasdfghjklyxcvbnm,_,-"
android:hint="Only letters, digits, _ and - allowed" />
<EditText
android:inputType="text"
android:digits="0,1,2,3,4,5,6,7,8,9,*,qwertzuiopasdfghjklyxcvbnm,_,-"
android:hint="Only letters, digits, _ and - allowed"
/>
上面的代码还将包括,
另外避免,
使用下面的代码:
<EditText
android:inputType="text"
android:digits="0123456789qwertzuiopasdfghjklyxcvbnm_-"
android:hint="Only letters, digits, _ and - allowed"
/>