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

时间:2016-08-29 09:48:39

标签: android string split android-edittext android-textinputlayout

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

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();
        }
    }
});

这是我的布局视图。

<!--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>

我基于拆分字符串here

1 个答案:

答案 0 :(得分:1)

属性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来动态添加或删除InputFilter周围的EditText

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