對於android的界面來說,在Material Design問世之前,作爲一個android開發人員,不得不承認,ios的某些控件帶來的畫面感要略勝一籌,但是自從Material Design出現,我們彷彿看到了android界面上的一大進步,首先我們來看看TextInputLayout的特點。
這個控件的意圖很簡單,它類似於scrollview,只能容許包含一個子佈局,而且是EditText,它相當於是對EditText的一個動畫的優化了,一方面是當我們點擊EditText時,如果設置了hint,那麼這個hint則會以動畫的形式擠到輸入的內容的上方,這對界面來說是一個很大的優點,它既保留了輸入框應該有的提示,有添加了動畫,下面我們看看具體怎麼用。
首先,添加依賴:
compile 'com.android.support:appcompat-v7:25.2.0' compile 'com.android.support:design:25.2.0'
然後在這裏界面的使用佈局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="#e3e3e3" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="@dimen/activity_horizontal_margin" android:orientation="vertical"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0.5" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center" android:text="Welcome" android:textSize="30sp" android:textColor="#333333"/> </RelativeLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0.5" android:orientation="vertical"> <android.support.design.widget.TextInputLayout android:id="@+id/usernameWrapper" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textEmailAddress" android:hint="Username"/> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/passwordWrapper" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/usernameWrapper" android:layout_marginTop="4dp"> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:hint="Password"/> </android.support.design.widget.TextInputLayout> <Button android:id="@+id/btn" android:layout_marginTop="4dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Login"/> </LinearLayout> </LinearLayout>
要實現動畫效果,我們需要在代碼中調用sethint,如下:
TextInputLayout usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper); TextInputLayout passwordWrapper = (TextInputLayout) findViewById(R.id.passwordWrapper); usernameWrapper.setHint("Username"); passwordWrapper.setHint("Password");
最後的效果圖如下: