Android中限制並統計字數的EditText

design包已經出來有幾年了,其中就有TextInputLayout&TextInputEditText,動效前

<android.support.design.widget.TextInputLayout
    android:id="@+id/rl_phone"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:theme="@style/TextInputLayoutLineColor"
    app:counterEnabled="true"
    app:counterMaxLength="11">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/welcome_Phone_edit"
        android:layout_width="300dp"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_gravity="center_horizontal"
        android:hint="@string/phoneNum"
        android:imeOptions="actionNext"
        android:inputType="number"
        android:maxLength="11"
        android:singleLine="true"
        android:textCursorDrawable="@drawable/shape_cursor"/>

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

TextInputLayout能爲輸入框提供簡單動畫,在獲取焦點後提示問題會有一個簡單的位移縮放動效,
動效後
如果是輸入密碼類型的話給TextInputEditText設置android:inputType=”textPassword”後會自動出現眼睛的按鈕,能控制密碼是否可見。
通過 app:counterEnabled=”true” app:counterMaxLength=”11” 兩句限制了最大字符長度,如果TextInputEditText不設置android:maxLength的話,超過11個字符就會變色提示,但仍然能輸入大於11個字符的數據,設置了android:maxLength後超過字符後輸入無效。

在這個控件出現之前只能設置android:maxLength來限制字符長度,想要統計輸入字符個數都是通過addTextChangedListener來監聽字符變化後顯示在另一個textView中,

meditTextwords.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mtextContentNum.setText(String.valueOf((200 - editable.toString().trim().length())));
            }
        });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章