我有一個EditText給用戶comments.Now我想輸入限制將是500字。 這意味着用戶可以寫評論最多500字。 我該如何執行此操作?請幫幫我。EditText輸入限制500字?
2
A
回答
9
您可能使用TextWatcher
來觀看文本,並且不允許它超過500個單詞。
實現你TextWatcher
:
final int MAX_WORDS = 500;
final EditText editBox = (EditText) findViewById(<your EditText field>);
editBox.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// Nothing
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Nothing
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
String[] words = s.toString().split(" "); // Get all words
if (words.length > MAX_WORDS) {
// Trim words to length MAX_WORDS
// Join words into a String
editBox.setText(wordString);
}
}
});
注:您可能需要使用的東西從this thread加入String[]
到wordString
。
但是,這是不是世界上最有效的方法,坦率地說,誠實。實際上,在每個密鑰條目上創建整個String
的陣列可能是非常重要的,特別是在較舊的設備上。
我個人建議的是,你允許用戶輸入任何他們想要的,然後在提交時驗證它的字數。如果是<=500
單詞,請允許它,否則拒絕它,並給他們一些消息(一個Toast
?),告訴他們。
最後,通過字數驗證是非常困難的。請記住,有些東西可以用作空格,但不會被
(字符160)這樣的東西拾取。你是遠更好地選擇一個字符限制和限制字段使用已提供的maxLength
答案。
-1
我試過在XML文件中寫入這一點,但它不工作:
這一件作品肯定,實際上是一個更好的解決問題,你也可以將它用於自定義驗證規則:
InputFilter maxChars = new InputFilter.LengthFilter(500); // 500個字符 editText.setFilters(new InputFilter [] {maxChars});