TextInputLayout 使用

TextInputLayout主要是作为EditText的容器,从而为EditText生成一个浮动的Label,当用户点击EditText的时候,EditText中的hint字符串会自动移到EditText的左上角。
TextInputLayout如何使用

xml布局

<?xml version="1.0" encoding="utf-8"?>


<android.support.design.widget.TextInputLayout
android:layout_width=“match_parent”
android:layout_marginTop=“20dp”
android:layout_height=“wrap_content”>

</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width=“match_parent”
android:layout_marginTop=“20dp”
android:layout_height=“wrap_content”>

</android.support.design.widget.TextInputLayout>

●设置最大字符数及错误提示
xml
<android.support.design.widget.TextInputLayout
android:layout_width=“match_parent”
android:layout_marginTop=“20dp”
app:counterEnabled=“true” //设置为true才能显字符数
app:counterMaxLength=“5” //设置最大字符数为5
app:counterOverflowTextAppearance="@style/HintError" //设置超出字符数后提示文字的颜色,如果不设置默认为@color/colorAccent的颜色
android:layout_height=“wrap_content”>

</android.support.design.widget.TextInputLayout>

style文件(设置超出字符数的文字提示颜色为红色)

●设置错误提示文字
xml
<android.support.design.widget.TextInputLayout
android:layout_width=“match_parent”
android:layout_marginTop=“20dp”
app:errorEnabled=“true” //设置为true
android:id="@+id/textinputlayout_email"
android:layout_height=“wrap_content”>

</android.support.design.widget.TextInputLayout>

java代码
editText_email=findViewById(R.id.et_email);
textInputLayout =findViewById(R.id.textinputlayout_email);
editText_email.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if(!RegexUtils.isEmail(charSequence)){
                textInputLayout.setError("邮箱格式错误");
                textInputLayout.setErrorEnabled(true);
            }else {
                textInputLayout.setErrorEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

●设置密码是否可见
xml
<android.support.design.widget.TextInputLayout
android:layout_width=“match_parent”
android:layout_marginTop=“20dp”
app:errorEnabled=“true”
app:passwordToggleEnabled=“true” //设置为true
android:id="@+id/textinputlayout_password"
android:layout_height=“wrap_content”>

</android.support.design.widget.TextInputLayout>

猜你喜欢

转载自blog.csdn.net/weixin_41620505/article/details/91540761
今日推荐