android - 使用 TextWatcher 在 EditText 中设置最大字数限制

标签 android string split android-edittext android-textinputlayout

我有一个用 TextInputLayout 包装的 EditText - 这将获得组织的使命/愿景。

TextInputLayout 将通知剩余的单词数,如果遇到空格,它将拆分字符串。

问题是它不计算单词,而是计算字符。

这是我的示例代码:

appCompatEditTextEventThirdContents.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

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

    }

    @Override
    public void afterTextChanged(Editable s) {
        final int maxWords = 500;
        String[] words = s.toString().split(" ");
        int currentWords = words.length;
        try{
            if (currentWords < maxWords) {
                appCompatEditTextEventThirdContents.setHint("Third Paragraph " + (maxWords - currentWords) + "left");
            }
            else if (currentWords >= maxWords ){
                appCompatEditTextEventThirdContents.setHint("Exceeded 500 words.");

            }
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
    }
});

这是我的布局 View 。

<!--THIRD PARAGRAPH-->
<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textInputThirdEventParag"
    android:hint="@string/paragThird"
    android:layout_below="@+id/textInputSecondEventParag"
    android:layout_centerHorizontal="true">

    <android.support.v7.widget.AppCompatEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextPG3"
        android:scrollbars="vertical|horizontal"
        android:minLines="5"
        android:maxLines="10"
        android:maxLength="500"
        android:singleLine="false"/>

</android.support.design.widget.TextInputLayout>

I base splitting strings here .

最佳答案

maxLength 属性限制了 EditText 中的字符。因此,在您的情况下,您需要删除该属性。您还需要删除 maxLines 属性。

<android.support.v7.widget.AppCompatEditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/editTextPG3"
    android:scrollbars="vertical|horizontal"
    android:minLines="5"
    android:singleLine="false"/>

现在,您需要 InputFilterTextWatcher 来设置最大字数限制。

像这样准备您的 InputFilter

private InputFilter mInputFilter;

// Helping functions to dynamically add or remove filters from your EditText
private void forceFilter(EditText mEditText, int charCount) {
    mInputFilter = new InputFilter.LengthFilter(charCount);
    mEditText.setFilters(new InputFilter[] { mInputFilter });
}

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

现在声明一个获取字数的函数

private int getWordsCount(String input) {
    String trim = input.trim();
    if (trim.isEmpty())
        return 0;
    return trim.split("\\s+").length; // Separate string by spaces
}

现在您必须添加 TextWatcher 以动态添加或删除 EditText 周围的 InputFilter

private final int MAX_WORD_LIMIT = 500;
private EditText mEditText = (EditText) findViewById(R.id.your_edit_text);

appCompatEditTextEventThirdContents.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        int totalWordCount = getWordCount(s.toString());

        // totalWordCount = 0 means a new word is going to start
        if (count == 0 && totalWordCount >= MAX_WORD_LIMIT) {
            forceFilter(mEditText, mEditText.getText().length());
            appCompatEditTextEventThirdContents.setHint("Exceeded 500 words.");
        } else {
            removeFilter(mEditText);
            appCompatEditTextEventThirdContents.setHint("Third Paragraph " + (maxWords - currentWords) + "left");
        }
    }

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

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

你不能用这个处理粘贴事件中的最大字数。如果你也想过滤粘贴事件,你可以看看 here .

关于android - 使用 TextWatcher 在 EditText 中设置最大字数限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39203233/

相关文章:

android - Firemonkey:如何检测操作系统(Android/iOS)何时关闭

php - 将文本拆分为单个单词

Android - Gradle 同步失败 : org/jetbrains/kotlin/kapt/idea/KaptGradleModelorg/jetbrains/kotlin/kapt/idea/KaptGradleModel

android - 如何从浏览器获取url字符串

android - 与 Linux 相比,Android 有任何网络限制吗?

perl - 如何拆分三个不同的分隔符然后 ucfirst 每个结果[]?

python - 如何用数字和字母拆分 Python 字符串?

c# - 不带空格的字符串长度 (C#)

c - 如何改进这种trim-half-string算法?

c# - 在 List<string> 中搜索字符串 .StartsWith()