TextInputLayout有以下几点
1、TextInputLayout和Edittext,TextInputEdittext结合使用。
2、setErrorEnabled(boolean):设置是否显示编辑框的错误提示,setError(CharSequence):设置编辑框的错误提示文字。
如上图当输入框未输入文字时显示Eddittext设置的提示文字,当输入文字时上方会显示蓝色的TextInputLayout的提示文字。如果输入错误的话输入框会变红色,并且下方会有红色的提示文字。
布局代码如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/background_color" android:orientation="vertical"> <include layout="@layout/head" /> <android.support.design.widget.TextInputLayout android:id="@+id/textinputlayout_til" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:hint="请输入11位手机号-Edittext"> <EditText android:id="@+id/input_et" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/white_empty_shape" android:inputType="phone" android:textColor="@color/text_main_color" android:textColorHint="@color/text_three_color" android:textSize="@dimen/middle" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/tie_til" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:hint="请输入11位手机号-TextInputEditText" android:textColorHint="@color/text_second_color"> <android.support.design.widget.TextInputEditText android:id="@+id/input_tie" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/white_empty_shape" android:inputType="phone" android:textColorHint="@color/text_three_color" android:textSize="@dimen/middle" /> </android.support.design.widget.TextInputLayout> </LinearLayout>在布局中可以设置各自提示文字的字体大小,文字颜色等等。
Java代码如下
editTIL = (TextInputLayout) findViewById(R.id.textinputlayout_til); // editTIL.setHint("请输入11位手机号"); input_et = (EditText) findViewById(R.id.input_et); input_et.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() != 11) { editTIL.setError("请输入正确的手机号"); editTIL.setErrorEnabled(true); } else { editTIL.setErrorEnabled(false); } } @Override public void afterTextChanged(Editable s) { } }); input_tie = (TextInputEditText) findViewById(R.id.input_tie); tie_til = (TextInputLayout) findViewById(R.id.tie_til); input_tie.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() != 11) { tie_til.setError("请输入正确的手机号"); tie_til.setErrorEnabled(true); } else { tie_til.setErrorEnabled(false); } } @Override public void afterTextChanged(Editable s) { } });