android TextInputLayout在将error设置为null后更改EditText样式

时间:2015-12-09 15:20:36

标签: android android-textinputlayout

我第一次使用新的Android的小部件TextInputLayout,它非常好但我使用setError方法遇到了一些问题

这是我的xml

<android.support.design.widget.TextInputLayout
    android:id="@+id/userData_txtNameWrapper"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:textColorHint="@color/light_gray"
    app:hintTextAppearance="@style/TextAppearence.App.TextInputLayout">
    <EditText
        android:id="@+id/userData_txtName"
        style="@style/bold_textbox_style"
        android:layout_width="match_parent"
        android:layout_height="@dimen/textinut_height"
        android:layout_margin="5dp"
        android:hint="name"
        android:imeOptions="actionNext"
        android:inputType="text"
        android:paddingTop="10dp"
        android:textSize="@dimen/medium_text"/>
</android.support.design.widget.TextInputLayout>

发生了什么:

当我跑

setError("error message") 

整个EditText背景和提示文本颜色变为红色,因为这里很好。问题是我运行时

setError(null) 

EditText的样式与原始样式完全不同。

开始情况:

未聚焦 unfocused 重点 focused

AFTER setError("mandatory field")

enter image description here

AFTER setError(null)

enter image description here

我做了很多研究,但找不到任何有用的东西,问题究竟应该是什么?

更新

调查setError()方法的android源代码我发现了这个

public void setError(@Nullable CharSequence error) {
    if (!mErrorEnabled) {
        if (TextUtils.isEmpty(error)) {
            // If error isn't enabled, and the error is empty, just return
            return;
        }
        // Else, we'll assume that they want to enable the error functionality
        setErrorEnabled(true);
    }
    if (!TextUtils.isEmpty(error)) {
        ViewCompat.setAlpha(mErrorView, 0f);
        mErrorView.setText(error);
        ViewCompat.animate(mErrorView)
                .alpha(1f)
                .setDuration(ANIMATION_DURATION)
                .setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR)
                .setListener(new ViewPropertyAnimatorListenerAdapter() {
                    @Override
                    public void onAnimationStart(View view) {
                        view.setVisibility(VISIBLE);
                    }
                })
                .start();
        // Set the EditText's background tint to the error color
        mErrorShown = true;
        updateEditTextBackground();
        updateLabelVisibility(true);
    } else {
        if (mErrorView.getVisibility() == VISIBLE) {
            ViewCompat.animate(mErrorView)
                    .alpha(0f)
                    .setDuration(ANIMATION_DURATION)
                    .setInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR)
                    .setListener(new ViewPropertyAnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(View view) {
                            view.setVisibility(INVISIBLE);
                            updateLabelVisibility(true);
                        }
                    }).start();
            // Restore the 'original' tint, using colorControlNormal and colorControlActivated
            mErrorShown = false;
            updateEditTextBackground();
        }
    }


    private void updateEditTextBackground() {
        if (mErrorShown && mErrorView != null) {
            // Set the EditText's background tint to the error color
            ViewCompat.setBackgroundTintList(mEditText,
                    ColorStateList.valueOf(mErrorView.getCurrentTextColor()));
        } else if (mCounterOverflowed && mCounterView != null) {
            ViewCompat.setBackgroundTintList(mEditText,
                    ColorStateList.valueOf(mCounterView.getCurrentTextColor()));
        } else {
            final TintManager tintManager = TintManager.get(getContext());
            ViewCompat.setBackgroundTintList(mEditText,
                    tintManager.getTintList(R.drawable.abc_edit_text_material));
        }
    }

并调试代码我发现在updateEditTextBackground()中执行的代码片段如下

final TintManager tintManager = TintManager.get(getContext());
ViewCompat.setBackgroundTintList(mEditText,
        tintManager.getTintList(R.drawable.abc_edit_text_material));

似乎android是任意取代EditText的背景色调。我尝试使用此代码在名为abc_edit_text_material.xml的drawable文件夹中创建一个文件

<inset xmlns:android="http://schemas.android.com/apk/res/android"
       android:insetLeft="@dimen/abc_edit_text_inset_horizontal_material"
       android:insetRight="@dimen/abc_edit_text_inset_horizontal_material"
       android:insetTop="@dimen/abc_edit_text_inset_top_material"
       android:insetBottom="@dimen/abc_edit_text_inset_bottom_material">

    <selector>
        <item android:state_enabled="false" android:drawable="@color/white"/>
        <item android:state_pressed="false" android:state_focused="false" android:drawable="@color/white"/>
        <item android:drawable="@color/white"/>
    </selector>

</inset>

但这是setError(null)

之后的结果

enter image description here

此外我注意到只有当我运行setError(“错误消息”)然后运行setError(null)

时才会出现问题

更新2 这是我用来验证输入的代码

public boolean validateInputs() {
    mTxtNameWrapper.setError(null);
    mTxtLastNameWrapper.setError(null);
    mTxtEmailWrapper.setError(null);
    mTxtCountryWrapper.setError(null);
    mTxtIdCardWrapper.setError(null);
    mTxtFiscalCodeWrapper.setError(null);
    mLblDocTypeError.setVisibility(View.GONE);
    if (Strings.isNullOrEmpty(mTxtName.getText().toString())) {
        mTxtNameWrapper.setError("Mandatory field");
        return false;
    }
    if (Strings.isNullOrEmpty(mTxtLastName.getText().toString())) {
        mTxtLastNameWrapper.setError("Mandatory field");
        return false;
    }
    if (Strings.isNullOrEmpty(mTxtEmail.getText().toString())) {
        mTxtEmailWrapper.setError("Mandatory field");
        return false;
    }
    if (!android.util.Patterns.EMAIL_ADDRESS.matcher(mTxtEmail.getText().toString()).matches()) {
        mTxtEmailWrapper.setError("Invalid email format");
        return false;
    }
    if (Strings.isNullOrEmpty(mTxtCountry.getText().toString())) {
        mTxtCountryWrapper.setError("Mandatory field");
        return false;
    }
    if (mRdgIdType.getCheckedRadioButtonId() == -1) {
        mLblDocTypeError.setText("Select a document type");
        mLblDocTypeError.setVisibility(View.VISIBLE);
        return false;
    }
    if (Strings.isNullOrEmpty(mTxtIdCard.getText().toString())) {
        mTxtIdCardWrapper.setError("Mandatory field");
        return false;
    }
    if (Strings.isNullOrEmpty(mTxtFiscalCode.getText().toString())) {
        mTxtFiscalCodeWrapper.setError("Mandatory field");
        return false;
    }
    return true;
}

我疯了!!!

6 个答案:

答案 0 :(得分:6)

我遇到了类似的问题并找到了一个简单的解决方案。如果我们将自定义背景drawable / color设置为EditText内的TextInputLayout,则会出现此问题。对此的解决方案是对TextInputLayout进行子类化并覆盖setError()drawableStateChanged()方法,并将我们的自定义drawable / color设置为EditText's背景。例如,我的EditText's背景有一个圆角可绘制集,下面是我的子类,

public class RoundedBorderedTextInputLayout extends TextInputLayout {
    private Context context;

    public RoundedBorderedTextInputLayout(Context context) {
        super(context);
        this.context = context;
    }

    public RoundedBorderedTextInputLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    public RoundedBorderedTextInputLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
    }

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();

        EditText editText = getEditText();
        if(editText != null) {
            editText.setBackground(ContextCompat.getDrawable(this.context, R.drawable.custom_rounded_edittext));
        }
    }

    @Override
    public void setError(@Nullable final CharSequence error) {
        super.setError(error);

        EditText editText = getEditText();
        if(editText != null) {
            editText.setBackground(ContextCompat.getDrawable(this.context, R.drawable.custom_rounded_edittext));
        }
    }
}

然后在xml中使用自定义类

<com.example.RoundedBorderedTextInputLayout
                android:id="@+id/text_input_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <EditText
                    android:id="@+id/edittext"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textPassword"/>

  </com.example.RoundedBorderedTextInputLayout>

希望这会有所帮助。快乐的Android编码:)

答案 1 :(得分:4)

将错误设置为null后,您只需将颜色更改回您想要的颜色即可。类似的东西:

yourEditText.setError(null);
yourEditText.getBackground().mutate().setColorFilter(
            ContextCompat.getColor(getContext() , R.color.somecolor),
            PorterDuff.Mode.SRC_ATOP);

答案 2 :(得分:4)

这是support:design:23.2.0(可能是旧版本)中的一个错误,它被报告为问题here 并已在23.3.0 update

中修复

答案 3 :(得分:0)

设置textinput的样式

<style name="TextAppearence.App.TextInputLayout" parent="@android:style/TextAppearance">
        <item name="android:textColor">@color/colorPrimaryDark</item>
        <item name="android:textColorHint">@color/colorPrimaryDark</item>
        <item name="android:textSize">14sp</item>
        <item name="colorAccent">@color/colorPrimaryDark</item>
        <item name="colorControlNormal">@color/colorPrimaryDark</item>
        <item name="colorControlActivated">@color/colorPrimaryDark</item>
    </style>

将下面的代码放在setError(null)

的位置
     txt.setError(null);

//for plain white backgorund  
    editText.setBackgroundColor(getResources().getColor(android.R.color.white));

//or if you want any other than
editText.setBackgroundResource(R.drawable.border);

其中border是我的xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background_shape">
    <stroke android:width="2dp" android:color="#ff207d94" />
    <padding android:left="2dp"
        android:top="2dp"
        android:right="2dp"
        android:bottom="2dp" />
    <corners android:radius="5dp" />
    <solid android:color="#ffffffff" />
</shape>

答案 4 :(得分:0)

我有一个解决这个问题的技巧:

1,新增一个类扩展android.support.design.widget.TextInputEditText; 2,覆盖getBackground()方法,使其返回null;

因为TextInputLayout中的方法updateEditTextBackground()将判断editText的背景drawable是否为null,现在总是返回null,结果是editText的背景不会被错误文本颜色改变。

答案 5 :(得分:0)

在此link

中仅获得了setError的解决方案

即。我使用了自定义TextInputLayout

这是我的自定义TextInputLayout

<com.adminworksite.Design.NoChangingBackgroundTextInputLayout
                        android:id="@+id/city_til_of_job_create"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/tv_placeholder_five"
                        android:layout_marginLeft="@dimen/left_right"
                        android:layout_marginRight="@dimen/left_right"
                        app:counterEnabled="true"
                        app:counterMaxLength="35">

                        <EditText
                            android:id="@+id/city_et_of_job_create"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:background="@drawable/edittext_background"
                            android:inputType="text"
                            android:paddingLeft="@dimen/left_right"
                            android:paddingRight="@dimen/left_right" />
                    </com.adminworksite.Design.NoChangingBackgroundTextInputLayout>

但是如果我将长度限制设置为TextInputLayout 即。

app:counterEnabled="true"
app:counterMaxLength="35"

当限制超出时颜色仍会显示,并且颜色也会变为粉红色

所以我为它构建了一个解决方案,使用addTextChangedListener来编辑文本和 按代码设置背景

  

代码段

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() == 0) {
                    textInputLayout.setErrorEnabled(true);
                    textInputLayout.setError("Input should not be empty!");
                } else {
                    textInputLayout.setErrorEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                setBackgroundToEt(editText);
            }
        });


private void setBackgroundToEt(EditText editText) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            editText.setBackground(getResources().getDrawable(R.drawable.edittext_background));
        }
    }

最后在内部验证方法中,我再次使用set background来编辑我的editText

  

代码段:

private boolean validateInputs() {
//validation code...
setBackgroundToEt(editText);
}