1. 程式人生 > >android edittext 輸入字數限制 超過最大字數toast

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)。

 <EditText
        android:id="@+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"/>