简体   繁体   中英

Gradient Drawable - getting the Stroke Color programmatically

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> 

它在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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM