Android Design Support Library -- TextInputLayout, designsupplibrary Library
Cutting-edge
The previous article introduced how to use NavigationView. This chapter describes how to use TextInputLayout.
TextInputLayout -- EditText floating label
TextInputLayout is mainly used as the parent container of EditText and cannot be used separately. TextInputLayout solves the problem that the hint text disappears after the EditText input. When the user starts inputting the EditText, the text in the hint part will float above the EditText, you can also add a prompt when an error is entered, which is displayed below editText. The effect is as follows:
Procedure:
(1) xml Layout
<?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 call
Final TextInputLayout textInputLayout = (TextInputLayout) findViewById (R. id. usernameWrapper); textInputLayout. setHint ("Username"); EditText editText = textInputLayout. getEditText (); // The EditText control can be obtained directly through getEditText. addTextChangedListener (new TextWatcher () {@ Override public void beforeTextChanged (CharSequence s, int start, int count, int after) {if (s. length ()> 3) {// here we can add a regular expression to determine textInputLayout. setError ("Password error"); textInputLayout. setErrorEnabled (true); // It must be executed after the setError method} else {textInputLayout. setErrorEnabled (false); // if the condition is not met, set it to false.} @ Override public void onTextChanged (CharSequence s, int start, int before, int count) {}@ Override public void afterTextChanged (Editable s ){}});}
In addition, you can set the hint and error fonts by using the following two attributes: TextInputLayout.
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>