前沿 上一篇介紹了NavigationView的主要使用方式,本章主要介紹TextInputLayout的使用方式。 TextInputLayout——EditText懸浮標簽 TextInputLayout主要作為EditText的父容器來使用,不能單獨使用。TextInputLayout解...
前沿
上一篇介紹了NavigationView的主要使用方式,本章主要介紹TextInputLayout的使用方式。
TextInputLayout——EditText懸浮標簽
TextInputLayout主要作為EditText的父容器來使用,不能單獨使用。TextInputLayout解決了EditText輸入後hint文字消失的情況,當用戶在EditText開始輸入後,hint部分的文字會浮動到EditText的上方,而且還可以添加輸入錯誤時的提示信息,顯示在editText的下方,效果如下:
使用步驟:
(1)xml佈局
<?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代碼調用
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的字體
app:errorTextAppearance="@style/FloatingStyle"
app:hintTextAppearance="@style/FloatingStyle"
/style/FloatingStyle
<style name="FloatingStyle" parent="@android:style/TextAppearance"> <item name="android:textColor">@color/colorPrimaryDark</item> <item name="android:textSize">12sp</item> </style>