Do not change TextInputLayout background on error

前端 未结 4 1843
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 06:51

I would like to have an EditText with the background as a \"normal\" EditText but with the error handling of a TextInputEditText (error message appearing at the bottom, and

4条回答
  •  悲哀的现实
    2020-12-01 07:39

    I manage to resolve this myself by overriding TextInputLayout like this :

    public class NoChangingBackgroundTextInputLayout extends TextInputLayout {
        public NoChangingBackgroundTextInputLayout(Context context) {
            super(context);
        }
    
        public NoChangingBackgroundTextInputLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public NoChangingBackgroundTextInputLayout(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        public void setError(@Nullable CharSequence error) {
            ColorFilter defaultColorFilter = getBackgroundDefaultColorFilter();
            super.setError(error);
            //Reset EditText's background color to default.
            updateBackgroundColorFilter(defaultColorFilter);
        }
    
        @Override
        protected void drawableStateChanged() {
            ColorFilter defaultColorFilter = getBackgroundDefaultColorFilter();
            super.drawableStateChanged();
            //Reset EditText's background color to default.
            updateBackgroundColorFilter(defaultColorFilter);
        }
    
        private void updateBackgroundColorFilter(ColorFilter colorFilter) {
            if(getEditText() != null && getEditText().getBackground() != null)
                getEditText().getBackground().setColorFilter(colorFilter);
        }
    
        @Nullable
        private ColorFilter getBackgroundDefaultColorFilter() {
            ColorFilter defaultColorFilter = null;
            if(getEditText() != null && getEditText().getBackground() != null)
                defaultColorFilter = DrawableCompat.getColorFilter(getEditText().getBackground());
            return defaultColorFilter;
        }
    }
    

    So as we can see it, it reset the EditText's background to its default color after setError has been called but also in the method drawableStateChanged() because the red color filter is set when losing/getting the focus on an EditText with error too.

    I'm not convinced that this is the best solution but if I don't get any better solutions, I'll mark it as resolved in meantime.

提交回复
热议问题