转载自http://blog.csdn.net/feiduclear_up/article/details/46500865
该控件是用于EditView输入框的,主要解决之前EditView在获得焦点编辑时hint属性提示语消失,这一点在一个页
面有多个EditView输入框的时候不是很好,因为很有可能用户在输入多个EditView之后,不知道当前EditView需
要输入什么内容。为了解决这一问题,TextInputLayout就此诞生了。TextInputLayout是继承自LinearLayout容
器布局,因此我们需要将EditView包含在TextInputLayout之内才可以使用,言外之意:TextInputLayout不能单
独使用。废话不多说,先上效果图啊:
XML布局代码如下:
<android.support.design.widget.TextInputLayout
android:id="@+id/textInput"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/black"/>
</android.support.design.widget.TextInputLayout>
代码也可以看出TextInputLayout包裹着EditView。
为了达到以上效果,我们还需添加如下代码:
final TextInputLayout inputLayout = findView(R.id.textInput);
inputLayout.setHint("请输入姓名:");
EditText editText = inputLayout.getEditText();
editText.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()>4){
inputLayout.setErrorEnabled(true);
inputLayout.setError("姓名长度不能超过4个");
}else{
inputLayout.setErrorEnabled(false);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
TextInputLayout 不仅能让EditView的提示语上弹显示在EditView之上,而且还能把错误信息显示在EditView之下。
TextInputLayout常用的方法有如下:
- setHint():设置提示语。
- getEditText():得到TextInputLayout中的EditView控件。
- setErrorEnabled():设置是否可以显示错误信息。
- setError():设置当用户输入错误时弹出的错误信息。
注意点
- TextInputLayout不能单独使用,需要包裹EditView组件。
【转载请注明出处:http://blog.csdn.net/feiduclear_up/article/details/46500865 CSDN 废墟的树】