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

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


当前回答

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

其他回答

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

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

文档

实例

android:maxLength="10"

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" />
TextView tv = new TextView(this);
tv.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(250) });

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