
begin
if Length(Edit1.Text) >4 then
ShowMessage('超出范围')
end
一、限制输入个数长度,平时我们会使用下面这两种方法1、在 xml 文件中设置文本编辑框属性作字符数限制
如:android:maxLength="10" 即限制最大输入字符个数为10
2、在代码中使用InputFilter 进行过滤
//editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)})即限定最大输入字符数为20
也可在InputFilter里添加新方法
一、限制输入字符长度,1个GBK的汉字是2个字符,1个UTF-8的汉字是3个字符,暂时我们都统一处理1个汉字占2个字节来算
上代码:
etEditText.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) {
String inputMsg = s.toString().trim()
if (!TextUtils.isEmpty(inputMsg)) {
String limitMsg = WidgetUtil.getLimitInput(inputMsg, /**rightInfoMaxLen*/20)
if (!TextUtils.isEmpty(limitMsg)) {
if (!limitMsg.equals(inputMsg)) {
etEditText.setText(limitMsg)
etEditText.setSelection(limitMsg.length())
}
}
}
})
/**
* 限制文本输入
* @param inputStr
* @param maxLen
* @return
*/
public static String getLimitInput(String inputStr, int maxLen) {
int origLen = inputStr.length()
int bytesLen = 0//字节数
String temp
for (int i = 0i <origLeni++) {
temp = inputStr.substring(i, i + 1)
try {
if (temp.getBytes(Constants.Encode.UTF_8).length == 3 || temp.getBytes(Constants.Encode.GBK).length == 2) {
bytesLen += 2
} else {
bytesLen++
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace()
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)