Android如何设置最大值" word"对EditText的限制

时间:2015-03-03 04:04:40

标签: android android-edittext limit word

如何在Android EditText上设置最大字数限制我知道如何设置字符数限制,但我正在寻找字数限制

3 个答案:

答案 0 :(得分:11)

您需要向TextChangedListener添加EditText,然后应用InputFilter,请参阅以下代码。

edDesc.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        int wordsLength = countWords(s.toString());// words.length;
        // count == 0 means a new word is going to start
        if (count == 0 && wordsLength >= MAX_WORDS) {
            setCharLimit(edDesc, edDesc.getText().length());
        } else {
            removeFilter(edDesc);
        }

        tvWordCount.setText(String.valueOf(wordsLength) + "/" + MAX_WORDS);
        }

    @Override
    public void afterTextChanged(Editable s) {}
});

private int countWords(String s) {
    String trim = s.trim();
    if (trim.isEmpty())
        return 0;
    return trim.split("\\s+").length; // separate string around spaces
}

private InputFilter filter;

private void setCharLimit(EditText et, int max) {
    filter = new InputFilter.LengthFilter(max);
    et.setFilters(new InputFilter[] { filter });
}

private void removeFilter(EditText et) {
    if (filter != null) {
        et.setFilters(new InputFilter[0]);
        filter = null;
    }
}

您必须拦截粘贴事件,以便用户不能粘贴超过所需的字词。您可以拦截Android EditText粘贴事件[read more]

答案 1 :(得分:1)

我已经为EditText做了扩展功能,并且效果很好

fun EditText.addWordCounter(func: (wordCount: Int?) -> Unit) {

addTextChangedListener(object :TextWatcher{
    override fun afterTextChanged(s: Editable?) {}

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        val trim = s?.trim()
        val wordCount =
            if (trim?.isEmpty().orFalse()) 0 else trim?.split("\\s+".toRegex())?.dropLastWhile { it.isEmpty() }?.toTypedArray()?.size
        func(wordCount)
    }
})}

然后使用

etDesc.addWordCounter { wordCount ->
        Log.d(TAG, "addWordCounter: $wordCount")
    }

答案 2 :(得分:-2)

您可以限制在EditText中键入的单词。

只需添加此

android:maxLength="10"

完整代码:

 <EditText
        android:id="@+id/uname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:maxLength="10"/>

官方文件here

快乐编码:)