安卓如何在EditText中设置最大的“字数”限制

10
如何在Android的EditText上设置最大字数限制。我知道如何设置字符限制,但是我正在寻找字数限制
4个回答

18

您需要向您的EditText添加一个TextChangedListener,然后应用一个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粘贴事件[了解更多]


你仍然需要查看粘贴事件 :) - AZ_
当我想要更改现有单词的字符时,如果我已经输入了n个单词,它就会失败。由于字符限制过滤器,它不允许我继续输入。 - Daniyal Javaid
只要添加一个字符,编辑器就不会让你再添加更多字符,这个不起作用。 - Alberto M

3

我为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()!!or(false)) 0 else trim.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size

        func(wordCount)
    }
})}

然后像这样使用。
etDesc.addWordCounter { wordCount ->
        Log.d(TAG, "addWordCounter: $wordCount")
    }

0

binding.etSectionDesc.doAfterTextChanged { val count = binding.etSectionDesc.content().wordCount()

绑定.etSectionDesc.在文本更改后执行{ val count = binding.etSectionDesc.content().wordCount() }

        if (count >= ValidationConst.MAX_COURSE_DESC_LENGTH_SHOW) {
            setCharLimit(binding.etSectionDesc, binding.etSectionDesc.content().length)
        } else {
            removeFilter(binding.etSectionDesc)
        }

        binding.tvDescTotalChar.apply {
            text = count.toString()
            if (count < ValidationConst.MAX_COURSE_DESC_LENGTH_SHOW) {
                setTextColor(ContextCompat.getColor(context, R.color.black))
            } else {
                setTextColor(context.getAttrResource(R.attr.accentColor_Red))
            }
        }


    }

-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"/>

官方文档 在这里

编程愉快 :)


这将设置最大字符数,而非单词数。 - CACuzcatlan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接