前沿android
上一篇介紹了NavigationView的主要使用方式,本章主要介紹TextInputLayout的使用方式。app
TextInputLayout——EditText懸浮標籤ide
TextInputLayout主要做爲EditText的父容器來使用,不能單獨使用。TextInputLayout解決了EditText輸入後hint文字消失的狀況,當用戶在EditText開始輸入後,hint部分的文字會浮動到EditText的上方,並且還能夠添加輸入錯誤時的提示信息,顯示在editText的下方,效果以下:佈局
使用步驟:字體
(1)xml佈局spa
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <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:hint="Username" android:inputType="textEmailAddress" /> </android.support.design.widget.TextInputLayout> </RelativeLayout>
(2)Java代碼調用code
final TextInputLayout textInputLayout = (TextInputLayout) findViewById(R.id.usernameWrapper); textInputLayout.setHint("Username"); EditText editText = textInputLayout.getEditText();//直接經過getEditText()得到EditText控件便可 editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if (s.length() > 3) {//這裏能夠加入正則判斷 textInputLayout.setError("Password error"); textInputLayout.setErrorEnabled(true); //必定要在setError方法以後執行纔可 } else { textInputLayout.setErrorEnabled(false);//不知足條件須要設置爲false } } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { } }); }
此外能夠經過TextInputLayout以下兩個屬性來設置hint和error的字體xml
app:errorTextAppearance="@style/FloatingStyle"
app:hintTextAppearance="@style/FloatingStyle"
/style/FloatingStyleblog
<style name="FloatingStyle" parent="@android:style/TextAppearance"> <item name="android:textColor">@color/colorPrimaryDark</item> <item name="android:textSize">12sp</item> </style>