方法一:
// 输入框限制输入字数
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 on TextChanged(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);
}
}


});


方法二:
利用EditText可以设置filter的特性,自定义一个LengthFilter,当输入字数超过限制时 ,做出自定义的提示
// 输入框限制输入字数
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(Constant.TEXT_MAX) {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (source.length() > 0 && dest.length() == Constant.TEXT_MAX) {
if ((System.currentTimeMillis() - toastTime) > interval) {
toastTime = System.currentTimeMillis();
Toast
.makeText(KaguHomeActivity.this,
R.string.edit_content_limit,
Toast.LENGTH_SHORT).show();
}
}
if (dest.toString().equals(
getResources().getString(R.string.input_default_txt))) {
Bundle da ta = new Bundle();
da ta.putCharSequence("source", source);
Message message = textHandler.obtainMessage();
message.setData(da ta);
message.sendToTarget();
}

return super.filter(source, start, end, dest, dstart, dend);
}
};
editText.setFilters(filters);
private Handler textHandler = new Handler() {
@Override
public void handleMessage(Message msg) {

Bundle da ta = msg.getData();
CharSequence source = da ta.getCharSequence("source");
editText.setTextColor(Color.BLACK);
editText.setText(source);
editText.setSelection(source.length());
}
};

更多相关文章

  1. android 常用方法集合
  2. android radiobutton选中字体颜色改变的方法
  3. android 关闭数据连接方法
  4. 在Android 7.0上PopupWindow.showAsDropDown不起作用的解决方法
  5. Android --- 图片处理的方法
  6. android剪切圆角图片的方法
  7. android中数据存储的contentprovider的使用方法
  8. Android那些疑惑(2)-LayoutInflater中inflate方法参数的意义
  9. android 模拟器获取root权限的方法

随机推荐

  1. 使用EasyPermissions高效处理权限
  2. 设置界面android 设置界面
  3. speex算法在android上的移植
  4. 为菜鸟量身定制0基础android逆袭课程(颠覆
  5. 一分钟帮你提升Android(安卓)studio 编译
  6. 高效android编程
  7. 34、Android编写应用-从模板添加代码
  8. Android手机硬件信息的查看和软件安装方
  9. 自己实现的android树控件,android TreeVie
  10. Android(安卓)三种常用实现自定义圆形进