问题
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