1. 程式人生 > >登入輸入框限制長度改變按鈕顏色

登入輸入框限制長度改變按鈕顏色

MainActivity

//登入驗證
    private void init() {
        EditText pass_phone = findViewById(R.id.pass);   //手機號
        final Button commit = findViewById(R.id.commit);
        pass_phone.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) {
                 //按鈕可以點選 改變背景色
                commit.setEnabled((s.length() == 11));
            }

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

activity_main.xml

 <EditText
           android:id="@+id/pass"
           android:layout_width="0dp"
           android:layout_height="50dp"
           android:hint=" 請輸入手機號"
           android:textSize="25sp"
           android:numeric="integer"
           android:maxLength="11"
           app:layout_constraintLeft_toRightOf="@+id/text1"
           app:layout_constraintRight_toRightOf="parent"
           app:layout_constraintTop_toBottomOf="@+id/phone"
           />

    <Button
        android:id="@+id/commit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:enabled="false"
        android:text="下一步"
        android:background="@drawable/selector"
        android:textSize="25sp"
        app:layout_constraintTop_toBottomOf="@+id/pass"
        android:layout_marginTop="20dp"
        />

selecter.xml選擇器

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_enabled="false">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="#b3e9f3"/>
            <corners android:radius="15dp"/>

        </shape>
    </item>

    <item android:state_enabled="true">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="#b3e04d"/>
            <corners android:radius="15dp"/>

        </shape>
    </item>

</selector>