(一)简单的过滤
EditText已经提供了一些过滤输入的属性 1、通过inputType限定 android:inputType="textCapCharacters"//前3个输入普通字符 android:inputType="textCapWords"//单词首字母大小 android:inputType="textCapSentences"//仅第一个字母大写 android:inputType="textAutoCorrect"//前两个自动完成 android:inputType="textAutoComplete"//前两个自动完成 android:inputType="textMultiLine"//多行输入 android:inputType="textImeMultiLine"//输入法多行(不一定支持) android:inputType="textNoSuggestions"//不提示 android:inputType="textUri"//URI格式 android:inputType="textEmailAddress"//电子邮件地址格式 android:inputType="textEmailSubject"//邮件主题格式 android:inputType="textShortMessage"//短消息格式 android:inputType="textLongMessage"//长消息格式 android:inputType="textPersonName"//人名格式 android:inputType="textPostalAddress"//邮政格式 android:inputType="textPassword"//密码格式 android:inputType="numberPassword"//数字密码格式 android:inputType="textVisiblePassword"//密码可见格式 android:inputType="textWebEditText"//作为网页表单的文本格式 android:inputType="textFilter"//文本筛选格式 android:inputType="textPhonetic"//拼音输入格式 android:inputType="number"//数字格式 android:inputType="numberSigned"//有符号数字格式 android:inputType="numberDecimal"//可以带小数点的浮点格式 android:inputType="phone"//拨号键盘 android:inputType="datetime"//日期时间键盘 android:inputType="date"//日期键盘 android:inputType="time"//时间键盘
我们常用的有phone,number,numberSigned,numberDecimal等限定输入数字和textpassword,numberPassword格式. 除了inputType属性还有一个numeric属性(现在不推荐实用了,因为inputType已经包含了)
android:numeric="integer" android:numeric="signed" android:numeric="decimal"对应inputType的number,numberSigned,numberDecimal。2、通过单个属性 //为true限制输入电话号码 android:phoneNumber=”true” //为true限制输入电话号码 android:phoneNumber=”true” //为true限制输入密码 android:password="true"
myEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
mTextMaxlenght = 0;
Editable editable = s;
// System.out.println(editable.toString() + " eeeeee");
String str = s.toString().trim();
//得到最初字段的长度大小,用于光标位置的判断
int selEndIndex = Selection.getSelectionEnd(editable);
// 取出每个字符进行判断,如果是字母数字和标点符号则为一个字符加1,
//如果是汉字则为两个字符
for (int i = 0; i < str.length(); i++) {
char charAt = str.charAt(i);
textsize.setText(str.length() + " ");
//32-122包含了空格,大小写字母,数字和一些常用的符号,
//如果在这个范围内则算一个字符,
//如果不在这个范围比如是汉字的话就是两个字符
if (charAt >= 32 && charAt <= 122) {
mTextMaxlenght++;
} else {
mTextMaxlenght += 2;
}
// 当最大字符大于160时,进行字段的截取,并进行提示字段的大小
if (mTextMaxlenght > 160) {
// 截取最大的字段
String newStr = str.substring(0, i);
myEditText.setText(newStr);
// 设置新光标所在的位置
myEditText.setSelection(newStr.length());
Toast.makeText(ChuangZuoYe.this, "最大长度为160个字符或80个汉字!", Toast.LENGTH_SHORT).show();
return;
}
}
}
});