android edittext 输入字数限制 超过最大字数toast

1.不实时显示已经写入字体

        etEvaluateContent.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) {


                if (s.toString().trim().length() > maxLength) {
                    etEvaluateContent.setText(s.toString().substring(0, maxLength));
                    etEvaluateContent.setSelection(maxLength);
                    ToastUtil.showToastWithImg("您最多能输入200个字", R.mipmap.toast_error);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

2.实时显示已经写入字体个数

etSuggestContent.addTextChangedListener(new TextWatcher() {
            CharSequence input;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                input = s;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tvMaxCount.setText(String.format("%d/200", input.length()));
                if (input.length() > 199) {
                    ToastUtil.showToastWithImg("您最多能输入200个字", R.mipmap.toast_error);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

注意:以上两种类型方案均需要在xml文件中设置最大字数属性(maxLength)。

 "@+id/et_suggest_content"
        style="@style/text_normal_light"
        android:layout_width="0dp"
        android:layout_height="141dp"
        android:layout_marginTop="@dimen/dp_10"
        android:background="@color/white"
        android:gravity="top"
        android:hint="您可以在这里给我们建议帮助我们做的更好"
        android:maxLength="200"
        android:paddingBottom="@dimen/dp_27"
        android:paddingLeft="@dimen/app_margin"
        android:paddingRight="@dimen/app_margin"
        android:paddingTop="@dimen/dp_10"
        android:textColorHint="@color/hint"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

你可能感兴趣的:(Android)