Android: Change Shape Color in runtime

2020-01-24 11:35发布

I have a drawable that i use as a Background for a LinearLayout. I would like to change the color of this Shape in runtime. I have tried using several methods.. but none work.

I've followed the approach described here: http://www.anddev.org/android-2d-3d-graphics-opengl-problems-f55/change-shape-drawable-solid-color-t16798.html

But have the same problem... it doesnt crashes.. but the color doesnt change!

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#00A6C1" />
    <corners android:radius="@dimen/square_corners" />
</shape>

Snippet of code:

GradientDrawable drawable = (GradientDrawable) activity.getResources().getDrawable(R.drawable.blue_square_shape);


int color = ((Application) getApplication()).getColor();
drawable.setColor(color);

block.findViewById(R.id.blockSquare).setBackgroundDrawable(drawable);

findViewById(R.id.blockSquare).postInvalidate();

Any clue? I've passed the whole day googling... and it's getting pretty annoying...

UPDATE:

When i try to do the same to this Shape:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/shape" android:shape="rectangle">
    <gradient android:startColor="#1FBCCF" android:endColor="#06A4C1"
        android:angle="270" />
    <corners android:topLeftRadius="@dimen/footer_corners"
        android:topRightRadius="@dimen/footer_corners" />
</shape>

The color turns to black... what i guess tells it can be changed...

8条回答
爷、活的狠高调
2楼-- · 2020-01-24 12:25

This is what I'm doing in a live wallpaper where I modify a Drawable at runtime:

this.original = DrawableFactory.getDrawable(getContext().getResources(), objectName)[0];
originalBitmap = original.getBitmap();
copy = new BitmapDrawable(getContext().getResources(), original.getBitmap().copy(Bitmap.Config.ARGB_8888, true));
copyCanvas = new Canvas(copy.getBitmap());

Edit: Type declarations:

public Bitmap originalBitmap;
public BitmapDrawable original;
public BitmapDrawable copy;
public Canvas copyCanvas;

Edit 2:

Try this in that case:

int color = (0xFF000000 | yourParsedColor)

Then set that color.

查看更多
做自己的国王
3楼-- · 2020-01-24 12:29
GradientDrawable background = (GradientDrawable) titleTextView.getBackground();
background.setColor(getResources().getColor(R.color.some_color));

The setColor method correctly requests a redraw on the element (If in xml you used the <shape> element it will always become a GradientDrawable)

查看更多
登录 后发表回答