TextInputLayout輸入框控件的懸浮標籤

TextInputLayout也是5.0以後的效果,想要使用同樣需要在build中配置:

dependencies {
    compile 'com.android.support:design:23.3.0'
}
TextInputLayout可以用來顯示一個提示錯誤信息,把Hint放到EditText左上方等效果的一個佈局;

如果項目中有這類的需求,使用TextInputLayout實現起來非常方便;

使用方法也比較簡單,直接用TextInputLayout包裹EditText即可:

<android.support.design.widget.TextInputLayout
        android:id="@+id/til_user"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp">
        <EditText
            android:id="@+id/et_user"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="請輸入用戶名"/>
    </android.support.design.widget.TextInputLayout>
但是默認情況下,當你輸入文本的時候TextInputLayout只會將Hint移動到左上方,不會有錯誤提示,錯誤提示需要我們手動設置:

etUser= (EditText) findViewById(R.id.et_user);
        tilUser= (TextInputLayout) findViewById(R.id.til_user);

        //添加文本變化監聽
        etUser.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.length()>6){
                    //打開TextInputLayout異常提示
                    tilUser.setErrorEnabled(true);
                    //設置TextInputLayout異常提示信息
                    tilUser.setError("賬號最大長度爲6");
                }else {
                    //關閉TextInputLayout異常提示
                    tilUser.setErrorEnabled(false);
                }
            }

            @Override
            //輸入以後調用
            public void afterTextChanged(Editable s) {
            }
        });




點擊打開鏈接免費下載源碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章