限制EditText最多输入n位,设置EditText最大输入长度;

时间:2022-05-27 01:13:56

1、比较笨的方法:

/**
* 设置edittext最大的输入限制
* @param editText
* @param length
*/
private void setMaxLength(EditText editText , int length){
editText.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) {
String str = s.toString();
if (str.length()>length){
editText.setText(str.substring(0,length)); //截取前x位
editText.requestFocus();
editText.setSelection(editText.getText().length()); //光标移动到最后
}
} @Override
public void afterTextChanged(Editable s) { }
});
}

如果重复设置,需要清空前一个;这是edittext的源码;

    /**
* Adds a TextWatcher to the list of those whose methods are called
* whenever this TextView's text changes.
* <p>
* In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously
* not called after {@link #setText} calls. Now, doing {@link #setText}
* if there are any text changed listeners forces the buffer type to
* Editable if it would not otherwise be and does call this method.
*/
public void addTextChangedListener(TextWatcher watcher) {
if (mListeners == null) {
mListeners = new ArrayList<TextWatcher>();
} mListeners.add(watcher);
} /**
* Removes the specified TextWatcher from the list of those whose
* methods are called
* whenever this TextView's text changes.
*/
public void removeTextChangedListener(TextWatcher watcher) {
if (mListeners != null) {
int i = mListeners.indexOf(watcher); if (i >= 0) {
mListeners.remove(i);
}
}
}

2、简单实用:

 et.setFilters(new InputFilter[]{new NotChineseFilter(), new InputFilter.LengthFilter(4)}); //限制输入4位