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

有没有通过xml实现这一点的方法?


当前回答

您可以在EditText中使用android:maxLength=“10”。(此处限制为最多10个字符)

其他回答

您可以在EditText中使用android:maxLength=“10”。(此处限制为最多10个字符)

我使用的是“maxLength”,但它对我不起作用。因此,根据我的经验,我尝试了一些方法。我发现了问题。我必须申报身份证。然后:

android:id="@+id/editTextTest"
android:maxLength="10"

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);

科特林:

editText.filters += InputFilter.LengthFilter(maxLength)

以编程方式为Java尝试以下操作:

myEditText(new InputFilter[] {new InputFilter.LengthFilter(CUSTOM_MAX_LEN)});

xml中的简单方式:

android:maxLength="4"

如果您需要在xml编辑文本中设置4个字符,请使用

<EditText
    android:id="@+id/edtUserCode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxLength="4"
    android:hint="Enter user code" />