Android中限制EditText文本长度的最佳方法是什么?

843

如何在Android中限制EditText的文本长度?

是否可以通过XML实现此功能?


1
我想要设置EditText的最大字符数。起初并不明显文本长度限制是同一件事。(仅供另一位迷惑的旅行者参考)。 - Katedral Pillon
正确答案在这里:https://dev59.com/Lmct5IYBdhLWcg3wc9Eg#19222238。此答案限制长度并防止缓冲区在达到限制后持续填充,因此可以使您的退格键正常工作。 - Martin Konecny
22个回答

1597

29
哎呀!我也遇到了同样的问题。我在看代码,但是没有setMaxLength方法。 - hpique
1
这里的“Check here”是做什么用的?它只是链接到这个页面。 - what is sleep
5
@Vincy,你是错误的。maxLength 属性仍然有效。 - ashishduh
8
请注意,android:maxLength 等同于 InputFilter.LengthFilter,因此当程序atically更改其过滤器时,您也修改了其XML过滤器。 - mr5
25
对于那些认为它不起作用的人,请注意调用setFilters会停止android:maxLength的工作,因为它会覆盖XML设置的过滤器。换句话说,如果您以编程方式设置了任何过滤器,则必须全部以编程方式进行设置。 - Ian Newson
显示剩余2条评论

388

使用输入过滤器来限制文本视图的最大长度。

TextView editEntryView = new TextView(...);
InputFilter[] filterArray = new InputFilter[1];
filterArray[0] = new InputFilter.LengthFilter(8);
editEntryView.setFilters(filterArray);

9
如果某人已经创建了一些“InputFilter”,那么这将非常有用。它将覆盖XML文件中的“android:maxlength”,因此我们需要以此方式添加“LengthFilter”来限制输入长度。 - Seblis
4
我认为您的答案是最好的,因为它更具有活力,+1。 - Muhannad A.Alhariri
这个可以运行,我的情况是:abc.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(10)}); - dotrinh PM

227
EditText editText = new EditText(this);
int maxLength = 3;    
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});

这与安卓使用xml的方式类似。 - string.Empty
4
我该如何设置最小长度? - Akhila
@AkhilaMadari,可能需要使用TextWatcher - CoolMind

75

我曾经遇到这个问题,我认为我们需要一个清晰易懂的编程方式来实现这一点,而不会丢失已设置的过滤器。

在XML中设置长度:

正如被接受的答案正确地指出的那样,如果您想为EditText定义一个固定的长度,并且将来不再更改它,只需在EditText的XML中定义即可:

android:maxLength="10"     

以编程方式设置长度

要以编程方式设置长度,您需要通过InputFilter进行设置。但是,如果您创建一个新的InputFilter并将其设置为EditText,则会失去所有其他已定义的过滤器(例如maxLines,inputType等),这些过滤器可能已经通过XML或编程方式添加。

因此,以下内容是错误的

editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
为了避免丢失之前添加的过滤器,您需要获取这些过滤器,在其中添加新的过滤器(在本例中为maxLength),然后将过滤器设置回EditText,代码如下:
```java InputFilter[] filters = editText.getFilters(); InputFilter[] newFilters = new InputFilter[filters.length + 1]; System.arraycopy(filters, 0, newFilters, 0, filters.length); newFilters[filters.length] = new InputFilter.LengthFilter(maxLength); editText.setFilters(newFilters); ```
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)

1
+1。不知道过滤器的存在。另一方面,比较了Java和Kotlin代码后,我想知道为什么人们还坚持使用Java进行Android开发xd。 - Xam
我在KOTLIN中做了类似这样的事情:myEdt.filters = arrayOf(InputFilter.LengthFilter(MAX_LENGTH)) - Rehan Dev

73

对于已经使用自定义输入过滤器并且想要限制最大长度的人们,需要注意:

当您在代码中分配输入过滤器时,所有先前设置的输入过滤器都将被清除,包括使用 android:maxLength 设置的过滤器。我发现当我尝试使用自定义输入过滤器防止在密码字段中使用一些不允许的字符时,设置了 setFilters 后,maxLength 不再生效了。解决方案是在代码中同时设置 maxLength 和自定义过滤器。像这样:

myEditText.setFilters(new InputFilter[] {
        new PasswordCharFilter(), new InputFilter.LengthFilter(20)
});

5
你可以首先获取现有的过滤器, InputFilter[] existingFilters = editText.getFilters();然后将你的过滤器与现有的过滤器一起添加。 - subair_a

41
TextView tv = new TextView(this);
tv.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(250) });

7
可以,只限于安卓操作系统。 - VAdaihiep

24

如果有其他人想知道如何实现此功能,这是我的扩展的EditTextEditTextNumeric

.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的所有其他方法和属性也同样有效。


1
如果我们将此添加到XML布局中会更好。当使用XML时,我遇到了错误。原因:android.view.InflateException: 二进制XML文件行#47:膨胀类com.passenger.ucabs.utils.EditTextNumeric时出错。 - Shihab Uddin
@Martynas,我也遇到了和Shihab_returns一样的错误,有解决方案吗? - Pranaysharma

23

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)

18

鉴于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 });
    }
}

3
你可能需要稍微更新一下代码。分配的数组大小应为curFilters.length + 1,在创建newFilters后,你没有将"this"设置为新分配的数组。 InputFilter newFilters[] = new InputFilter[curFilters.length + 1]; System.arraycopy(curFilters, 0, newFilters, 0, curFilters.length); this.setFilters(newFilters); - JavaCoderEx

16
//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()});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接