限制Android中EditText的文本长度

hpi*_*que 653 android maxlength android-edittext

什么是限制EditTextAndroid 文本长度的最佳方法?

有没有办法通过xml做到这一点?

Aus*_*son 1293

文档

android:maxLength="10"
Run Code Online (Sandbox Code Playgroud)

  • D'哦!这样的事情我也经历过.我在查看代码,并没有setMaxLength方法. (26认同)
  • 对于那些说不起作用的人来说,请注意调用`setFilters`会停止`android:maxLength`工作,因为它会覆盖XML设置的过滤器.换句话说,如果以编程方式设置任何过滤器,则必须以编程方式设置它们. (15认同)
  • 请注意,`android:maxLength`等同于`InputFilter.LengthFilter`,所以当以编程方式更改它的过滤器时,您也修改了它的XML过滤器. (6认同)
  • @Vincy,你错了.`maxLength`属性仍然有效. (5认同)

小智 330

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

TextView editEntryView = new TextView(...);
InputFilter[] filterArray = new InputFilter[1];
filterArray[0] = new InputFilter.LengthFilter(8);
editEntryView.setFilters(filterArray);
Run Code Online (Sandbox Code Playgroud)

  • 如果有人已经制作了一些`InputFilter`,这非常有用.它覆盖了xml文件中的`android:maxlength`,所以我们需要以这种方式添加`LengthFilter`. (5认同)
  • 我认为你的答案是最好的答案,因为它更有活力,+1 (4认同)

Emr*_*mza 192

EditText editText = new EditText(this);
int maxLength = 3;    
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
Run Code Online (Sandbox Code Playgroud)

  • 如何设置最小长度? (3认同)

got*_*o10 64

一个注谁正在使用一个自定义的输入滤波器和人民希望限制最大长度:

在代码中分配输入过滤器时,将清除所有先前设置的输入过滤器,包括一组android:maxLength.我在尝试使用自定义输入过滤器时发现了这一点,以防止使用我们在密码字段中不允许的某些字符.使用setFilters设置过滤器后,不再观察到maxLength.解决方案是以编程方式将maxLength和我的自定义过滤器设置在一起.像这样的东西:

myEditText.setFilters(new InputFilter[] {
        new PasswordCharFilter(), new InputFilter.LengthFilter(20)
});
Run Code Online (Sandbox Code Playgroud)

  • 您可以首先检索现有过滤器,InputFilter [] existingFilters = editText.getFilters(); 然后添加您的过滤器以及此现有过滤器 (4认同)

小智 38

TextView tv = new TextView(this);
tv.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(250) });
Run Code Online (Sandbox Code Playgroud)

  • 当然,仅限于Android (7认同)

小智 23

对于其他想知道如何实现这一点的人来说,这是我的扩展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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

final EditTextNumeric input = new EditTextNumeric(this);
input.setMaxLength(5);
input.setMaxValue(total_pages);
input.setMinValue(1);
Run Code Online (Sandbox Code Playgroud)

适用的所有其他方法和属性EditText当然也可以使用.


小智 17

由于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 });
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您可能希望稍微更新代码.分配的数组大小需要为curFilters.length + 1,在创建newFilters之后,您没有将"this"设置为新分配的数组.InputFilter newFilters [] = new InputFilter [curFilters.length + 1]; System.arraycopy(curFilters,0,newFilters,0,curFilters.length); this.setFilters(newFilters); (3认同)

Ric*_*rdo 15

我有这个问题,我认为我们缺少一个很好的解释方式,以编程方式执行此操作而不会丢失已设置的过滤器.

以XML格式设置长度:

正如所接受的答案正确陈述的那样,如果你想为EditText定义一个固定的长度,你将来不会进一步改变,只需在EditText XML中定义:

android:maxLength="10" 
Run Code Online (Sandbox Code Playgroud)

以编程方式设置长度

要以编程方式设置长度,您需要设置一个InputFilter.

Java的问题是:一旦你设置它,所有其他过滤器就会消失(例如maxLines,inputType等).为避免丢失先前的过滤器,您需要获取之前应用的过滤器,添加maxLength,并将过滤器设置回EditText,如下所示:

editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
Run Code Online (Sandbox Code Playgroud)

然而,Kotlin让每个人都更容易,你还需要将过滤器添加到现有的过滤器中,但是你可以通过简单的方法实现:

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);
Run Code Online (Sandbox Code Playgroud)


小智 15

//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()});
Run Code Online (Sandbox Code Playgroud)


Joã*_*los 11

XML

android:maxLength="10"
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

科特林:

editText.filters += InputFilter.LengthFilter(maxLength)
Run Code Online (Sandbox Code Playgroud)


nho*_*ass 9

XML

android:maxLength="10"

以编程方式:

int maxLength = 10;
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(maxLength);
yourEditText.setFilters(filters);
Run Code Online (Sandbox Code Playgroud)

注意:在内部,EditText & TextView 解析android:maxLengthXML 中的值并用于InputFilter.LengthFilter()应用它。

请参阅:TextView.java#L1564


小智 8

另一种可以实现此目的的方法是将以下定义添加到XML文件中:

<EditText
    android:id="@+id/input"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:maxLength="6"
    android:hint="@string/hint_gov"
    android:layout_weight="1"/>
Run Code Online (Sandbox Code Playgroud)

这会将EditText窗口小部件的最大长度限制为6个字符.


Ron*_*TLV 5

material.io中,您可以TextInputEditText结合使用TextInputLayout

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:counterEnabled="true"
    app:counterMaxLength="1000"
    app:passwordToggleEnabled="false">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/edit_text"
        android:hint="@string/description"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLength="1000"
        android:gravity="top|start"
        android:inputType="textMultiLine|textNoSuggestions"/>

</com.google.android.material.textfield.TextInputLayout>
Run Code Online (Sandbox Code Playgroud)

您可以使用drawable配置密码EditText:

密码范例

或者,您可以使用/不使用计数器来限制文本长度:

反例

依赖关系:

implementation 'com.google.android.material:material:1.1.0-alpha02'
Run Code Online (Sandbox Code Playgroud)