markbratanov
markbratanov

Reputation: 898

Trying to change the color of a shape used in textView background

I have a drawable oval defined in xml with a white background. I am setting this circle as the background resource of my textView inside my gridAdapter.

I want to change the color of the drawable circle by code, and I'm not having much luck. I have used .setColor , .setColorFilter and a variety of other hacks, but none have worked. The circle loads in the background of textView as white, it never seems to change.

Here I try to load the drawable and modify its color, and then add it as a background resource to the textView:

            int color = Color.parseColor(locationModel.col_line_color); // Color of the line

            GradientDrawable bgcircle = (GradientDrawable) gridContext.getResources().getDrawable(R.drawable.circle);
            bgcircle.mutate();
//          bgcircle.setColor(color);

            bgcircle.setColorFilter(color, Mode.SRC_ATOP);

            viewHolder.textView.setText((locationModel.col_line).toString());
            viewHolder.textView.setBackgroundResource(R.drawable.circle);

The XML for the drawable shape:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="oval">

   <solid 
       android:color="@android:color/white"/>

   <size 
       android:width="120dp"
       android:height="120dp"/>

</shape>

A lot of the tutorials call for .mutate() then to implement .setColorFilter(), but I haven't had much luck. I've tried changing the PorterDuff Mode to some alternatives, but the circles continue rendering white.

Any help/guidance would be appreciated.

Upvotes: 0

Views: 1725

Answers (1)

stinepike
stinepike

Reputation: 54692

Instead of tyring to modify the current xml drawable, Create the drawable in your code. you can also use ShapeDrawable if you dont need gradient.

ShapeDrawable drawable = new ShapeDrawable(new OvalShape());
drawable.getPaint().setColor(newColor);

Upvotes: 2

Related Questions