5

How can I change the <solid android:color= /> programmatically?

I defined a custom shape element: my_item.xml:

<shape android:shape="oval">
    <solid android:color="#FFFF0000"/>
</shape>

And reuse it in another layout: grid_view.xml:

<LinearLayout>
    <ImageView ... android:src="@drawable/my_item"
                   android:id="@+id/myitemid" />
</LinearLayout>

The following does not work:

public class ShapeItemAdapter extends BaseAdapter {

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
          view = inflter.inflate(R.layout.grid_view, null);
          ImageView shape = (ImageView) view.findViewById(R.id.myitemid);
          shape.setBackgroundColor(0xBCCACA); //does not work
    }
}
Amin Soheyli
  • 605
  • 2
  • 7
  • 16
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • Have you checked [this](https://stackoverflow.com/questions/17823451/set-android-shape-color-programmatically) before ask ? – Piyush Jul 24 '17 at 12:00

4 Answers4

5

I turned out none of the answers provided here have been correct. Important is: use getDrawable() on the shape, not getBackground().

GradientDrawable shape = (GradientDrawable) icon.getDrawable();
shape.setColor(Color.BLACK);
membersound
  • 81,582
  • 193
  • 585
  • 1,120
2

Try This:-

Get your drawable from resources and change shape color.Then you can set as a background of image view.

      GradientDrawable drawable = (GradientDrawable) mContext.getResources()
            .getDrawable(R.drawable.todo_list_circle);
    drawable.mutate();
    drawable.setColor(mColor);
Anshika Bansal
  • 320
  • 2
  • 9
0

try this

ImageView shape = (ImageView) view.findViewById(R.id.myitemid);
GradientDrawable bgShape = (GradientDrawable)shape.getBackground();
bgShape.setColor(Color.BLACK);
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
0

Get ShapeDrawable and set color:

ImageView shape = (ImageView) view.findViewById(R.id.myitemid);
ShapeDrawable shapeDrawable = (ShapeDrawable) shape.getBackground();
shapeDrawable.getPaint().setColor(ContextCompat.getColor(context,R.color.my_color));

You may wait until layout has been drawn:

 ViewTreeObserver to = shape.getViewTreeObserver();
 to.addOnGlobalLayoutListener (new OnGlobalLayoutListener() {
     @Override
     public void onGlobalLayout() {
         layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
         ImageView shape = (ImageView) view.findViewById(R.id.myitemid);
         ShapeDrawable shapeDrawable = (ShapeDrawable) shape.getBackground();
         shapeDrawable.getPaint().setColor(ContextCompat.getColor(context,R.color.my_color));
     }
 });
Fori
  • 475
  • 5
  • 15