簡體   English   中英

Android 如何設置 EditText 的最大“字數”限制

[英]Android How to set maximum "word" limit on EditText

如何設置最大字數限制 Android EditText我知道如何設置字符限制,但我正在尋找字數限制

您需要將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;
    }
}

您必須攔截 Paste 事件,以便用戶不能粘貼超過要求的單詞。 可以攔截Android EditText Paste事件[閱讀全文]

我已經為 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")
    }

binding.etSectionDesc.doAfterTextChanged { 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))
            }
        }


    }

您可以限制在 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"/>

官方文檔在這里

快樂編碼:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM