如何在Android中限制EditText
的文本长度?
是否可以通过XML实现此功能?
如何在Android中限制EditText
的文本长度?
是否可以通过XML实现此功能?
maxLength
属性仍然有效。 - ashishduhandroid:maxLength
等同于 InputFilter.LengthFilter
,因此当程序atically更改其过滤器时,您也修改了其XML过滤器。 - mr5setFilters
会停止android:maxLength
的工作,因为它会覆盖XML设置的过滤器。换句话说,如果您以编程方式设置了任何过滤器,则必须全部以编程方式进行设置。 - Ian Newson使用输入过滤器来限制文本视图的最大长度。
TextView editEntryView = new TextView(...);
InputFilter[] filterArray = new InputFilter[1];
filterArray[0] = new InputFilter.LengthFilter(8);
editEntryView.setFilters(filterArray);
EditText editText = new EditText(this);
int maxLength = 3;
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
TextWatcher
。 - CoolMind我曾经遇到这个问题,我认为我们需要一个清晰易懂的编程方式来实现这一点,而不会丢失已设置的过滤器。
在XML中设置长度:
正如被接受的答案正确地指出的那样,如果您想为EditText定义一个固定的长度,并且将来不再更改它,只需在EditText的XML中定义即可:
android:maxLength="10"
以编程方式设置长度
要以编程方式设置长度,您需要通过InputFilter
进行设置。但是,如果您创建一个新的InputFilter并将其设置为EditText
,则会失去所有其他已定义的过滤器(例如maxLines,inputType等),这些过滤器可能已经通过XML或编程方式添加。
因此,以下内容是错误的:
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
为了避免丢失之前添加的过滤器,您需要获取这些过滤器,在其中添加新的过滤器(在本例中为maxLength),然后将过滤器设置回EditText,代码如下:InputFilter[] editFilters = editText.getFilters();
InputFilter[] newFilters = new InputFilter[editFilters.length + 1];
System.arraycopy(editFilters, 0, newFilters, 0, editFilters.length);
newFilters[editFilters.length] = new InputFilter.LengthFilter(maxLength);
editText.setFilters(newFilters);
Kotlin 让任何人都更容易,您只需要将过滤器添加到已经存在的过滤器中即可,但您可以通过简单的方式实现:
Kotlin 然而为每个人都提供了更简单的方法,您只需要将筛选器添加到已经存在的筛选器中即可,但您可以通过以下简单方式实现:
editText.filters += InputFilter.LengthFilter(maxLength)
对于已经使用自定义输入过滤器并且想要限制最大长度的人们,需要注意:
当您在代码中分配输入过滤器时,所有先前设置的输入过滤器都将被清除,包括使用 android:maxLength
设置的过滤器。我发现当我尝试使用自定义输入过滤器防止在密码字段中使用一些不允许的字符时,设置了 setFilters
后,maxLength
不再生效了。解决方案是在代码中同时设置 maxLength
和自定义过滤器。像这样:
myEditText.setFilters(new InputFilter[] {
new PasswordCharFilter(), new InputFilter.LengthFilter(20)
});
TextView tv = new TextView(this);
tv.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(250) });
如果有其他人想知道如何实现此功能,这是我的扩展的EditText
类EditTextNumeric
。
.setMaxLength(int)
- 设置最大数字位数
.setMaxValue(int)
- 限制最大整数值
.setMin(int)
- 限制最小整数值
.getValue()
- 获取整数值
import android.content.Context;
import android.text.InputFilter;
import android.text.InputType;
import android.widget.EditText;
public class EditTextNumeric extends EditText {
protected int max_value = Integer.MAX_VALUE;
protected int min_value = Integer.MIN_VALUE;
// constructor
public EditTextNumeric(Context context) {
super(context);
this.setInputType(InputType.TYPE_CLASS_NUMBER);
}
// checks whether the limits are set and corrects them if not within limits
@Override
protected void onTextChanged(CharSequence text, int start, int before, int after) {
if (max_value != Integer.MAX_VALUE) {
try {
if (Integer.parseInt(this.getText().toString()) > max_value) {
// change value and keep cursor position
int selection = this.getSelectionStart();
this.setText(String.valueOf(max_value));
if (selection >= this.getText().toString().length()) {
selection = this.getText().toString().length();
}
this.setSelection(selection);
}
} catch (NumberFormatException exception) {
super.onTextChanged(text, start, before, after);
}
}
if (min_value != Integer.MIN_VALUE) {
try {
if (Integer.parseInt(this.getText().toString()) < min_value) {
// change value and keep cursor position
int selection = this.getSelectionStart();
this.setText(String.valueOf(min_value));
if (selection >= this.getText().toString().length()) {
selection = this.getText().toString().length();
}
this.setSelection(selection);
}
} catch (NumberFormatException exception) {
super.onTextChanged(text, start, before, after);
}
}
super.onTextChanged(text, start, before, after);
}
// set the max number of digits the user can enter
public void setMaxLength(int length) {
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(length);
this.setFilters(FilterArray);
}
// set the maximum integer value the user can enter.
// if exeeded, input value will become equal to the set limit
public void setMaxValue(int value) {
max_value = value;
}
// set the minimum integer value the user can enter.
// if entered value is inferior, input value will become equal to the set limit
public void setMinValue(int value) {
min_value = value;
}
// returns integer value or 0 if errorous value
public int getValue() {
try {
return Integer.parseInt(this.getText().toString());
} catch (NumberFormatException exception) {
return 0;
}
}
}
示例用法:
final EditTextNumeric input = new EditTextNumeric(this);
input.setMaxLength(5);
input.setMaxValue(total_pages);
input.setMinValue(1);
当然,适用于EditText
的所有其他方法和属性也同样有效。
Xml
android:maxLength="10"
Java:
InputFilter[] editFilters = editText.getFilters();
InputFilter[] newFilters = new InputFilter[editFilters.length + 1];
System.arraycopy(editFilters, 0, newFilters, 0, editFilters.length);
newFilters[editFilters.length] = new InputFilter.LengthFilter(maxLength);
editText.setFilters(newFilters);
Kotlin:
editText.filters += InputFilter.LengthFilter(maxLength)
鉴于goto10的观察,我编写了以下代码以防止在设置最大长度时丢失其他过滤器:
/**
* This sets the maximum length in characters of an EditText view. Since the
* max length must be done with a filter, this method gets the current
* filters. If there is already a length filter in the view, it will replace
* it, otherwise, it will add the max length filter preserving the other
*
* @param view
* @param length
*/
public static void setMaxLength(EditText view, int length) {
InputFilter curFilters[];
InputFilter.LengthFilter lengthFilter;
int idx;
lengthFilter = new InputFilter.LengthFilter(length);
curFilters = view.getFilters();
if (curFilters != null) {
for (idx = 0; idx < curFilters.length; idx++) {
if (curFilters[idx] instanceof InputFilter.LengthFilter) {
curFilters[idx] = lengthFilter;
return;
}
}
// since the length filter was not part of the list, but
// there are filters, then add the length filter
InputFilter newFilters[] = new InputFilter[curFilters.length + 1];
System.arraycopy(curFilters, 0, newFilters, 0, curFilters.length);
newFilters[curFilters.length] = lengthFilter;
view.setFilters(newFilters);
} else {
view.setFilters(new InputFilter[] { lengthFilter });
}
}
//Set Length filter. Restricting to 10 characters only
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(MAX_LENGTH)});
//Allowing only upper case characters
editText.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
//Attaching multiple filters
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(MAX_LENGTH), new InputFilter.AllCaps()});