在Android中限制EditText文本长度的最佳方法是什么?
有没有通过xml实现这一点的方法?
在Android中限制EditText文本长度的最佳方法是什么?
有没有通过xml实现这一点的方法?
当前回答
文档
实例
android:maxLength="10"
其他回答
实现此目的的另一种方法是将以下定义添加到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"/>
这将限制EditText小部件的最大长度为6个字符。
xml中的简单方式:
android:maxLength="@{length}"
要以编程方式设置它,可以使用以下函数
public static void setMaxLengthOfEditText(EditText editText, int length) {
InputFilter[] filters = editText.getFilters();
List arrayList = new ArrayList();
int i2 = 0;
if (filters != null && filters.length > 0) {
int filtersSize = filters.length;
int i3 = 0;
while (i2 < filtersSize) {
Object obj = filters[i2];
if (obj instanceof LengthFilter) {
arrayList.add(new LengthFilter(length));
i3 = 1;
} else {
arrayList.add(obj);
}
i2++;
}
i2 = i3;
}
if (i2 == 0) {
arrayList.add(new LengthFilter(length));
}
if (!arrayList.isEmpty()) {
editText.setFilters((InputFilter[]) arrayList.toArray(new InputFilter[arrayList.size()]));
}
}
这很好。。。
android:maxLength=“10”
这将只接受10个字符。
我曾经遇到过这个问题,我认为我们缺少一种经过充分解释的方法,在不丢失已经设置的过滤器的情况下,通过编程实现这一点。
在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[] 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)
在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>
您可以使用drawbable配置密码EditText:
或者,可以使用/不使用计数器限制文本长度:
附属国:
implementation 'com.google.android.material:material:1.1.0-alpha02'