我想将EditText限制为仅限于(a-z,A-Z,0-9,space,。和其他一些)特定字符。
如果用户尝试输入列表之外的其他一些字符,则不应在edittext中显示。
有没有办法做到这一点?
答案 0 :(得分:5)
试试这个:
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))) {
return "";
}
}
return null;
}
};
edit.setFilters(new InputFilter[]{filter});
检查How can I filter ListView data when typing on EditText in android
答案 1 :(得分:4)
这是你的解决方案......
只需将字符添加到您想要allowed
final String allowed = "abcdefghijklmnopqrstuvwxyz";
final EditText editText = (EditText)findViewById(R.id.edit001);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
char currentChar = s.charAt(start);
System.out.println(currentChar);
if(allowed.contains(Character.toString(currentChar)))
{
//Nothing to do
}
else
{
editText.setText(editText.getText().toString().substring(0, editText.getText().toString().length()-1));
int position = editText.length();
Editable etext = editText.getText();
Selection.setSelection(etext, position);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
答案 2 :(得分:0)
您可以使用此
yourEditText.addTextChangedListener()
然后,您会看到用户输入是否符合您的限制,并选择要显示的字符。