Android Material Design控件學習(三)——使用TextInputLayout實現酷市場登錄效果


前言

前兩次,我們學習了

今天我們繼續MD控件的學習和使用。在學習之前,我們先來看一下酷市場的登錄效果。

實現這種效果的正是我們今天的主角——TextInputLayout。

學習

不管學習什么,首先看它的官方文檔。這是最權威,最高效的學習途徑。

文檔地址:http://developer.android.com/reference/android/support/design/widget/TextInputLayout.html

可以看到,TextInputLayout繼承自LinearLayout。一般將EditText和它的子類包含在內,以便用戶在輸入文本時,且當提示文本被隱藏時顯示一個浮動的標簽。

也支持通過setErrorEnabled(boolean)和setError(CharSequence)方法來顯示錯誤提示。

用法

TextInputLayout使用起來非常簡單,兩部搞定

  • 1.編寫XML布局文件,將EditText包含在內即可。
 <android.support.design.widget.TextInputLayout
            android:id="@+id/textInputLayoutName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="30dp">

            <EditText
                android:id="@+id/editTextName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/hint_name"
                android:textColorHint="@color/colorGray"
                />
        </android.support.design.widget.TextInputLayout>
  • 2.編寫邏輯代碼
    本來不需要這一步的,因為這控件存在一個bug,當清空之前輸錯的內容后,提示錯誤的紅色文字並不會消失。

我在Google和StackOverFlow上找了很久,這貌似是Google的bug。可參考 https://code.google.com/p/android/issues/detail?id=190355

為了解決這個bug,就需要我們監聽EditText的輸入變化了,具體處理看代碼。

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

            }

            @Override
            public void afterTextChanged(Editable s) {
                checkName(s.toString(),false);
            }
        });
/**
 *若用戶名為空且用戶是想登錄,提示錯誤,返回false。不為空,錯誤設為null
 */
 private boolean checkName(CharSequence name,boolean isLogin) {
        if(TextUtils.isEmpty(name)) {
            if(isLogin) {
                mTextInputLayoutName.setError(getString(R.string.error_login_empty));
                return false;
            }
        }else{
            mTextInputLayoutName.setError(null);
        }
        return true;
    }

實現效果:

具體代碼我上傳到Github了,https://github.com/JohnTsaiAndroid/CoolMarket

歡迎star&fork


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM