GradientDrawable setColors用于较旧的API级别

时间:2013-01-09 21:07:35

标签: android

是否可以在比API 16(JellyBean)更低的API级别的形状中设置渐变的颜色数组?

我目前正在使用:

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

效果很好,但我希望支持API Level 8(Froyo)或10(Gingerbread v2)。

1 个答案:

答案 0 :(得分:5)

我认为没有一种简单的方法可以做到这一点,所以我建议这样做:根据旧参数创建一个新的GradientDrawable(适用于16以下的API) 。感谢@StephenNiedzielski指出这里的缺陷 - 在API 16下面无法使用getOrientation()

如果没有Reflection,就没有办法做到这一点,因为你需要drawable的方向以便重新创建它。如果您已经拥有方向,则可以执行以下操作:

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);
}

因此,如果没有这些信息,你必须在16以下的API上使用Reflection。虽然它很骇人听闻,但它是相当安全的,因为那些API 的实现不应该永远改变(因为它们'不再被更新)。

如果它适合您的喜好,您可以使用Reflection to access the GradientState inner class。基本上,您需要模拟gd.mGradientState.mOrientation方法执行的调用getOrientation()(如评论中所述)。由于这两个都是私人的,你必须use Reflection