TextInputLayout是MD中的一種登錄界面忆畅,它有一個特點類似ScrollView就是它的內(nèi)部只能有一個控件盏檐,而這個控件只能是EditText螃诅。接下來說下它的用法:
首先添加依賴
compile 'com.android.support:appcompat-v7:25.0.1' //兼容低版本的浮動動畫
compile 'com.android.support:design:25.0.1' //引入design庫
xml中布局代碼
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:focusable="false"
android:padding="10dp"
android:focusableInTouchMode="true">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="用戶名"
android:textColorHint="#5D4037">
<EditText
android:textColor="#5D4037"
android:theme="@style/CustomEditText"
android:id="@+id/editone"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:hint="密碼"
android:inputType="textPassword"
android:textColorHint="#5D4037">
<EditText
android:theme="@style/CustomEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.design.widget.TextInputLayout>
<Button
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="登錄"/>
</LinearLayout>
Paste_Image.png
幾點注意事項
- 取消EditText的默認(rèn)獲取焦點
EditText默認(rèn)是獲取焦點的或南,這導(dǎo)致剛進(jìn)入此頁面古劲,用戶名就會上浮,并且鍵盤也默認(rèn)被拉出蛮浑。怎樣改變這種默認(rèn)設(shè)置唠叛,當(dāng)我們點擊時才出現(xiàn)上述的狀態(tài)呢?就是在EditText的父控件加兩行代碼沮稚。
android:focusable="false" //不能獲取焦點
android:focusableInTouchMode="true" //當(dāng)觸摸時才獲取焦點
- 更改EditText的hint默認(rèn)顏色
在TextInputLayout中通過下面這個屬性
android:textColorHint="#5D4037"
- 更改EditText的下滑線顏色
EditText下滑線有默認(rèn)的顏色艺沼,當(dāng)獲取焦點后又會有另一種默認(rèn)的顏色,怎樣自定義兩種狀態(tài)下的顏色蕴掏,需要我們自己寫一個style障般,然后通過EditText的theme屬性引用這個style调鲸。
<style name="CustomEditText" parent="Theme.AppCompat.Light">
<item name="colorControlNormal">#5D4037</item> //正常情況下線的顏色
<item name="colorControlActivated">#00BCD4</item> //獲取焦點后的顏色
</style>
- 怎樣更改hint浮上去后的顏色?
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item> //更改這里的顏色
</style>
Paste_Image.png
- 如果賬戶是手機(jī)號挽荡,可以加入字符計數(shù)藐石,在TextInputLayout中加入
app:counterEnabled="true" //是否計數(shù)
app:counterMaxLength="11" //最大長度
- 密碼時加入眼睛的圖標(biāo),在TextInputLayout中加入
app:passwordToggleEnabled="true"
如果想自定義圖標(biāo)
app:passwordToggleDrawable="@drawable/bg"
Paste_Image.png