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

來自: http://www.cnblogs.com/JohnTsai/p/5173926.html

前言

前兩次,我們學習了

今天我們繼續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></pre> 
  • 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; }</pre>

實現效果:

</div>

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

歡迎star&fork

</div>

 本文由用戶 DulcieGolds 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!