GradientDrawable setColors for older API levels

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-19 04:51:12

问题


Is it possible to set the colors array of a gradient in a shape on a lower API level than API 16 (JellyBean)?

I'm currently using:

GradientDrawable gd = (GradientDrawable)this.getBackground();
int[] colors = {0xFFFF0000, 0xFFCC0099};
gd.setColors(colors);

Which works great, but I am hoping to support API Level 8 (Froyo) or 10 (Gingerbread v2).


回答1:


I don't think there is an easy way of doing this, so here's what I'd suggest: Create a new GradientDrawable based on the parameters of the old one (for APIs below 16). Thanks to @StephenNiedzielski for pointing out the flaw here—getOrientation() is not available below API 16.

There is no way to do this without Reflection, as you need the orientation of the drawable in order to create it anew. If you already have the orientation, you can do this:

GradientDrawable gd = (GradientDrawable) getBackground();
int[] colors = {0xFFFF0000, 0xFFCC0099};
if (android.os.Build.VERSION.SDK_INT >= 16) {
    gd = gd.mutate(); // For safe resource handling
    gd.setColors(colors);
} else {
    // Fallback for APIs under 16.
    GradientDrawable ngd = new GradientDrawable(/* Orientation variable */, colors);
    // You may have to set other qualities of `ngd` here to make it match.
    setBackgroundDrawable(ngd);
}

So, without that information, you'd have to use Reflection on APIs below 16. While it's hacky, it's reasonably safe since the implementations of those APIs shouldn't ever change (since they're no longer being updated).

If it suits your fancy, you can use Reflection to access the GradientState inner class. Basically, you would need to emulate the call gd.mGradientState.mOrientation (as mentioned in the comments) that the getOrientation() method performs. As both of those are private, you'd have to use Reflection.



来源:https://stackoverflow.com/questions/14246499/gradientdrawable-setcolors-for-older-api-levels

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!