三种方式去限制EditView的字数
2015-09-22 16:47
225 查看
方法一:利用TextWatcher
Java代码
![](http://androidstudy.iteye.com/images/icon_star.png)
editText.addTextChangedListener(new TextWatcher() {
private CharSequence temp;
private boolean isEdit = true;
private int selectionStart ;
private int selectionEnd ;
@Override
public void beforeTextChanged(CharSequence s, int arg1, int arg2,
int arg3) {
temp = s;
}
@Override
public void onTextChanged(CharSequence s, int arg1, int arg2,
int arg3) {
}
@Override
public void afterTextChanged(Editable s) {
selectionStart = editText.getSelectionStart();
selectionEnd = editText.getSelectionEnd();
Log.i("gongbiao1",""+selectionStart);
if (temp.length() > Constant.TEXT_MAX) {
Toast.makeText(KaguHomeActivity.this,
R.string.edit_content_limit, Toast.LENGTH_SHORT)
.show();
s.delete(selectionStart-1, selectionEnd);
int tempSelection = selectionStart;
editText.setText(s);
editText.setSelection(tempSelection);
}
}
});
方法二:利用InputFilter
Java代码
![](http://androidstudy.iteye.com/images/icon_star.png)
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(100)}); //其中100最大输入字数
方法三:在XML中设定
Xml代码
![](http://androidstudy.iteye.com/images/icon_star.png)
<EditText
.
.
.
android:maxLength="100"
/>
Java代码
![](http://androidstudy.iteye.com/images/icon_star.png)
editText.addTextChangedListener(new TextWatcher() {
private CharSequence temp;
private boolean isEdit = true;
private int selectionStart ;
private int selectionEnd ;
@Override
public void beforeTextChanged(CharSequence s, int arg1, int arg2,
int arg3) {
temp = s;
}
@Override
public void onTextChanged(CharSequence s, int arg1, int arg2,
int arg3) {
}
@Override
public void afterTextChanged(Editable s) {
selectionStart = editText.getSelectionStart();
selectionEnd = editText.getSelectionEnd();
Log.i("gongbiao1",""+selectionStart);
if (temp.length() > Constant.TEXT_MAX) {
Toast.makeText(KaguHomeActivity.this,
R.string.edit_content_limit, Toast.LENGTH_SHORT)
.show();
s.delete(selectionStart-1, selectionEnd);
int tempSelection = selectionStart;
editText.setText(s);
editText.setSelection(tempSelection);
}
}
});
方法二:利用InputFilter
Java代码
![](http://androidstudy.iteye.com/images/icon_star.png)
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(100)}); //其中100最大输入字数
方法三:在XML中设定
Xml代码
![](http://androidstudy.iteye.com/images/icon_star.png)
<EditText
.
.
.
android:maxLength="100"
/>
相关文章推荐
- NOIP模拟9.19总结
- 限制内容长度(CSS,jQuery)
- JS实现鼠标双击页面向下滚动,单击停止的特效
- POJ 1144 Network
- 马良建模学习笔记——软包制作七、八
- ecshop二次开发文件目录大全
- [读书笔记-GPU GEMS C1] Effective Water Simulation from Physical Models
- Objective-C------NSDictionary、NSMutableDictionary字典对象用法总结
- ubuntu下的usb 转串口的使用
- 将cocos2dx导入Android工程
- HI3516A stride的理解.
- redhat 解压.tgz文件
- android图片缓存实现(自定义ImageLoader)
- 2016去哪网笔试题二
- Thinkphp的query返回值的问题
- ecshop二次开发的简单实例说明
- 我的第一篇博文
- 一些容易被忽视的linux命令(二)
- VirtualBox中安装CentOS使得在ssh和外网都能正常链接
- 注册功能实现