在 Android 中限制 EditText 文本长度的最佳方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3285412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the best way to limit text length of EditText in Android
提问by hpique
What's the best way to limit the text length of an EditText
in Android?
EditText
在 Android 中限制文本长度的最佳方法是什么?
Is there a way to do this via xml?
有没有办法通过xml来做到这一点?
回答by Austin Hanson
回答by jerry
use an input filter to limit the max length of a text view.
使用输入过滤器来限制文本视图的最大长度。
TextView editEntryView = new TextView(...);
InputFilter[] filterArray = new InputFilter[1];
filterArray[0] = new InputFilter.LengthFilter(8);
editEntryView.setFilters(filterArray);
回答by Emran Hamza
EditText editText = new EditText(this);
int maxLength = 3;
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
回答by goto10
A note to people who are already using a custom input filter and alsowant to limit the max length:
一个注谁正在使用一个自定义的输入滤波器和人民也希望限制最大长度:
When you assign input filters in code all previously set input filters are cleared, including one set with android:maxLength
. I found this out when attempting to use a custom input filter to prevent the use of some characters that we don't allow in a password field. After setting that filter with setFilters the maxLength was no longer observed. The solution was to set maxLength and my custom filter together programmatically. Something like this:
当您在代码中分配输入过滤器时,所有先前设置的输入过滤器都将被清除,包括一组带有android:maxLength
. 我在尝试使用自定义输入过滤器来防止在密码字段中使用某些我们不允许的字符时发现了这一点。使用 setFilters 设置该过滤器后,不再观察到 maxLength。解决方案是以编程方式将 maxLength 和我的自定义过滤器设置在一起。像这样的东西:
myEditText.setFilters(new InputFilter[] {
new PasswordCharFilter(), new InputFilter.LengthFilter(20)
});
回答by ramo2712
TextView tv = new TextView(this);
tv.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(250) });
回答by Ricardo
I have had this problem and I consider we are missing a well explained way of doing this programmatically without losing the already set filters.
我遇到了这个问题,我认为我们缺少一种很好的解释方式,可以在不丢失已经设置的过滤器的情况下以编程方式执行此操作。
Setting the length in XML:
在 XML 中设置长度:
As the accepted answer states correctly, if you want to define a fixed length to an EditText which you won't change further in the future just define in your EditText XML:
正如接受的答案正确指出的那样,如果您想为 EditText 定义一个固定长度,以后不会进一步更改,只需在 EditText XML 中定义:
android:maxLength="10"
Setting the length programmatically
以编程方式设置长度
To set the length programmatically you'll need to set it through an InputFilter
. But if you create a new InputFilter and set it to the EditText
you will lose all the other already defined filters (e.g. maxLines, inputType, etc) which you might have added either through XML or programatically.
要以编程方式设置长度,您需要通过InputFilter
. 但是,如果您创建一个新的 InputFilter 并将其设置为 the,EditText
您将丢失所有其他已定义的过滤器(例如 maxLines、inputType 等),这些过滤器可能是通过 XML 或以编程方式添加的。
So this is WRONG:
所以这是错误的:
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
To avoid losing previously added filters you need to get those filters, add the new one (maxLength in this case), and set the filters back to the EditText
as follow:
为避免丢失先前添加的过滤器,您需要获取这些过滤器,添加新过滤器(在本例中为 maxLength),并将过滤器设置回EditText
如下:
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);
Kotlinhowever made it easier for everyone, you also need to add the filter to the already existing ones but you can achieve that with a simple:
然而,Kotlin使每个人都更容易,您还需要将过滤器添加到已经存在的过滤器中,但您可以通过简单的方式实现:
editText.filters += InputFilter.LengthFilter(maxLength)
回答by Martynas Janu?kauskas
For anyone else wondering how to achieve this, here is my extended EditText
class EditTextNumeric
.
对于想知道如何实现这一目标的其他人,这是我的扩展EditText
课程EditTextNumeric
。
.setMaxLength(int)
- sets maximum number of digits
.setMaxLength(int)
- 设置最大位数
.setMaxValue(int)
- limit maximum integer value
.setMaxValue(int)
- 限制最大整数值
.setMin(int)
- limit minimum integer value
.setMin(int)
- 限制最小整数值
.getValue()
- get integer value
.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;
}
}
}
Example usage:
用法示例:
final EditTextNumeric input = new EditTextNumeric(this);
input.setMaxLength(5);
input.setMaxValue(total_pages);
input.setMinValue(1);
All other methods and attributes that apply to EditText
, of course work too.
适用于 的所有其他方法和属性EditText
当然也适用。
回答by Tim Gallagher
Due to goto10's observation, I put together the following code to protected against loosing other filters with setting the max length:
由于 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 });
}
}
回答by Kishore Reddy
//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()});
回答by Jo?o Carlos
Xml
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)