限制Android中EditText
文本長度的最佳方法是什麼? android
有沒有辦法經過xml作到這一點? 編程
一個注誰正在使用一個自定義的輸入濾波器, 也但願限制最大長度的人: this
當您在代碼中分配輸入過濾器時,全部先前設置的輸入過濾器都會被清除,包括android:maxLength
一組。 在嘗試使用自定義輸入過濾器以防止使用某些密碼字段中不容許的字符時,我發現了這一點。 使用setFilters設置該過濾器後,再也不觀察到maxLength。 解決方案是經過編程將maxLength和個人自定義過濾器一塊兒設置。 像這樣: spa
myEditText.setFilters(new InputFilter[] { new PasswordCharFilter(), new InputFilter.LengthFilter(20) });
因爲goto10的觀察,我將如下代碼放在一塊兒,以防止經過設置最大長度而丟失其餘過濾器: code
/** * 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 }); } }
TextView tv = new TextView(this); tv.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(250) });
EditText editText = new EditText(this); int maxLength = 3; editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
實現此目的的另外一種方法是將如下定義添加到XML文件: 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個字符。 get