Gradient Drawable - getting the Stroke Color programmatically

829 views Asked by At

I have edit Text whose backgroud is as below :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="2dip"
    android:layout_height="2dip"
    android:shape="rectangle" >
    <corners
        android:radius="2dp"
        />
    <gradient
        android:angle="45"
        android:centerX="35%"
        android:centerColor="#fff"
        android:startColor="#fff"
        android:endColor="#fff"
        android:type="linear"
        />
    <padding
        android:left="0dp"
        android:top="0dp"
        android:right="0dp"
        android:bottom="0dp"
        />
    <size
        android:width="250dp"
        android:height="50dp"
        />
    <stroke
        android:width="1dp"
        android:color="@color/mygray"
        />
</shape> 

it create a gray line border around edit Editext

I need to change this color when there is validation error and set it to red. On addTextChangedListener i need to reset it to gray color.

below is my function of changing color

     public void changeBackgroudndOnEditTextChange(EditText ... editTexts){
            for(EditText editText:editTexts){
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                    }

                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    setBackground(editText,context.getResources().getColor(R.color.red_color));

                    }

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



private void setBackground(View v, int backgroundColor) {
        GradientDrawable shape = new GradientDrawable();
        shape.setSize(v.getWidth(), v.getHeight());
        shape.setStroke(5,backgroundColor);
        v.setBackgroundDrawable(shape);
    }

how can i put a check whether if background is Gray then only change it to red otherwise no need because it get called multiple times.

1

There are 1 answers

0
lionscribe On BEST ANSWER

You can simply save the last background set in a tag, and the check tag. Just add the following lines to the beginning of setBackground

Integer color = v.getTag();
if (color != null && color.intValue() == backgroundColor )
    return;
v.setTag(Integer.valueof(backgroundColor));