android TextInputLayout changes EditText style after setting error to null

后端 未结 6 1741
独厮守ぢ
独厮守ぢ 2020-12-31 11:00

for the first time I\'m using the new Android\'s widget TextInputLayout, it\'s very nice but I\'m facing some problem using setError method

this is my xml



        
6条回答
  •  无人及你
    2020-12-31 11:21

    I ran into similar problem and found a simple solution for it. This problem occurs if we set a custom background drawable/color to the EditText inside the TextInputLayout. Solution to this would be to subclass the the TextInputLayout and override the setError() and drawableStateChanged() methods and set our custom drawable/color as the EditText's background again. For Example, I had a rounded corner drawable set for my EditText's background, below is my subclass,

    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));
            }
        }
    }
    

    And then use your custom class in the xml,

    
    
                    
    
      
    

    Hope this helps. Happy Android coding :)

提交回复
热议问题