TextInputLayout使用

What is TextInputLayout

这个Layout是用来套在EditText外面的,换言之,TextInputLayout不能单独存在,必须配合EditText一起使用,那么它有什么功能?
一.设置提示语,在输入状态下提示语依然可见(在EditText上方)
二.设置错误提示语,当EditText中的内容不符合要求时,可以在EditText下方显示错误信息
效果如下

用法
xml中声明一个TextInputLayout(里面套一个EditText)

<android.support.design.widget.TextInputLayout
        android:id="@+id/input_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </android.support.design.widget.TextInputLayout>

java文件中

final TextInputLayout inputLayout= (TextInputLayout) findViewById(R.id.input_layout);
        inputLayout.setHint("请输入姓名");

        EditText text=inputLayout.getEditText();
        inputLayout.setErrorEnabled(true);
        text.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()>6){
                    inputLayout.setError("姓名长度不能大于6");
                }else{
                    inputLayout.setError(null);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

在其他博客中还看到有这样一种写法的

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s.length()>6){
                    inputLayout.setErrorEnabled(true);
                    inputLayout.setError("姓名长度不能大于6");
                }else{
                    //inputLayout.setErrorEnabled(false);
                    inputLayout.setErrorEnabled(false);
                }
            }

实测这种写法有BUG(在23.0.0下)
具体表现为第一次长度超过6时显示错误信息,然后小于6时错误信息消失,输入内容长度再度超过6时,错误信息不再显示。
看起来好像是一旦调用了setErrorEnabled(false);再次执行setErrorEnabled(true);都是无效的了。
google了一下也有相关讨论
Issue 190355: TextInputLayout setError() will not show an error after it is cleared
Maybe已经解决了?

posted @ 2016-07-15 19:39  xdzhcs  阅读(1654)  评论(0编辑  收藏  举报