標籤:
Google為了統一Android系統的視覺和使用體驗而提出的一個新的標準,這就是Android Design。為了讓舊的系統也能相容新的標準,Google提供了Android Design Support Library包,在此包中,Android提供了很多新的控制項。而TextInputLayout正是來自於Android Design Support Library包。
TextInputLayout是一個新的布局,從繼承樹上看,它繼承自LinearLayout,但是它並不支援android:orientation屬性,因為TextInputLayout和ScrollView一樣,只能在其中遷入唯一的控制項。另外從TextInputLayout這個布局的名稱可以猜出,這是一個專門針對文本輸入動作而設計的布局。所以TextInputLayout一般是EditText或者AutoCompleteTextView這樣的控制項,TextInputLayout為這些控制項提供了體驗更好的顯示和體驗效果。
這裡以一個包含EditText的樣本,示範一下TextInputLayout的用法和效果。其布局檔案如下:
<android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:counterEnabled="true" app:counterMaxLength="5" app:hintAnimationEnabled="true" app:counterOverflowTextAppearance="@android:style/TextAppearance.DeviceDefault.Large"> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:maxLines="1" android:hint="@string/prompt_password" android:singleLine="true" /></android.support.design.widget.TextInputLayout>
其中的app是為了使用Android Design Support Library包提供的新屬性,而進行的一個申明,只需要在布局檔案的根項目上引入以下的命名空間即可。
xmlns:app="http://schemas.android.com/apk/res-auto"
布局檔案設定完畢,運行效果如所示:
從運行結果可以看到,視覺效果明顯比單純的只用EditText好了不少。這裡TextInputLayout做了一下幾件事:
- 自動計算出一個Padding,為動畫,錯誤資訊以及字數統計留出足夠的顯示空間。
- 當EditText擷取到焦點時,以動畫的方式,將EditText中的hint移動到左上方,避免了單獨使用EditText時,提示資訊在擷取到焦點後就不顯示的糟糕體驗。
- 統計EditText字數,並動態更新顯示。
在TextInputLayout中,重要的屬性有以下幾個:
- counterEnabled:是否啟用計數器
- counterMaxLength:啟用計數器時,最大字數限制(僅僅用做顯示)
- counterOverflowTextAppearance:當字數超出計數器的最大限制時的字型格式
- hintAnimationEnabled:是否啟用hint動畫效果
- errorEnabled:是否顯示錯誤資訊
- errorTextAppearance:錯誤資訊的字型格式
歡迎轉載,轉載同時請尊重著作權,附上本文原文連結:點擊這裡
==============================
更多內容,歡迎查看本人部落格:林彥君的部落格
==============================
【進階篇】Android學習筆記——TextInputLayout