TextInputLayout

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做了一下幾件事:

  1. 自動計算出一個Padding,爲動畫,錯誤信息以及字數統計留出足夠的顯示空間。
  2. 當EditText獲取到焦點時,以動畫的方式,將EditText中的hint移動到左上方,避免了單獨使用EditText時,提示信息在獲取到焦點後就不顯示的糟糕體驗。
  3. 統計EditText字數,並動態更新顯示。

在TextInputLayout中,重要的屬性有以下幾個:

 

  • counterEnabled:是否啓用計數器
  • counterMaxLength:啓用計數器時,最大字數限制(僅僅用做顯示)
  • counterOverflowTextAppearance:當字數超出計數器的最大限制時的字體格式
  • hintAnimationEnabled:是否啓用hint動畫效果
  • errorEnabled:是否顯示錯誤信息
  • errorTextAppearance:錯誤信息的字體格式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章