TextInputLayout

萝らか妹 提交于 2019-12-06 18:48:38

TextInputLayout

TextInputLayout 是一个布局,仅可以添加一个子View且必须为ExitText。

TextInputLayout 为用户提供了两个比较有意思的方法

1.hint是EditText的一个很好的属性,当用户输入数据后,hint内容将自动消失。使用TextInputLayout用户输入数据后内容将不会直接隐藏,而是上浮继续显示;

2.用户输入信息错误,错误提示将直接显示在输入EditText下发。

示例代码:

布局代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

   android:layout_width="match_parent"

   android:layout_height="match_parent">


   <EditText

       android:id="@+id/original_edittext"

       android:layout_width="match_parent"

       android:layout_height="wrap_content"

       android:layout_below="@id/section_label"

       android:hint="请输入密码"

       />


   <android.support.design.widget.TextInputLayout

       android:id="@+id/text_input_layout"

       android:layout_width="match_parent"

       android:layout_height="wrap_content"

       android:layout_below="@id/original_edittext"

       >

       <EditText

           android:id="@+id/Test_edittext"

           android:layout_width="match_parent"

           android:layout_height="wrap_content"

           />

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


   <EditText

       android:layout_width="match_parent"

       android:layout_height="wrap_content"

       android:layout_below="@id/text_input_layout"

       android:hint="请输入密码"

       />


</RelativeLayout>


Java代码:

    final TextInputLayout textInputLayout = (TextInputLayout) rootView.findViewById(R.id.text_input_layout);

    textInputLayout.setHint("请输入帐号"); //动态设置hint信息,尝试在布局中进行设置为成功

    textInputLayout.getEditText().setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override

        public void onFocusChange(View v, boolean hasFocus) {

            if (!hasFocus) {

                textInputLayout.setError("格式有误"); //自动设置setErrorEnabled为true

            } else {

                textInputLayout.setErrorEnabled(false); //设置错误信息提示。由于提示信息是需要占据一定位置,因此这里设置错误提示不可用

                textInputLayout.setError(null); //设置错误提示信息为空

            }

        }

    });


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!