前沿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>