渐变 XML 可绘制中心不起作用

Gradient XML drawable center not working

我正在尝试创建一个 XML 渐变可绘制对象以匹配 Material Design guidelines

中提到的这种样式

这是我的 XML 代码:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:angle="270"
        android:centerY="30%"
        android:endColor="@android:color/transparent"
        android:startColor="#4d000000"
        android:type="linear"/>
</shape>

我也尝试过将 centerY 设置为 0.3,但没有成功。可绘制对象在预览中始终看起来相同。

有人可以告诉我如何实现这种风格吗?提前致谢。

我不太明白你的错误。您可能首先必须设置 centerColor。如果您还没有查看文档,请查看:

https://developer.android.com/reference/android/graphics/drawable/GradientDrawable.html

但在使用 XML 可绘制的线性渐变之前,我建议您使用 Roman Nuriks 尝试解决此问题。在这里查看更多: https://plus.google.com/+RomanNurik/posts/2QvHVFWrHZf 他通过使用 Drawable 的 Java 实现解决了这个问题。与任何其他可绘制对象一样工作。

试试这个:

<gradient
    android:angle="270"
    android:centerColor="#b6babd"
    android:endColor="@android:color/transparent"
    android:startColor="#62471a"
    android:centerY="30%"
    />

我将 centerColor 设置为另一种颜色只是为了让您看看效果如何,但您可以更改为透明。

centerY 属性适用于 centerColor

centerX/centerY 不设置 centerColor 将无法工作。

试试这个:

<gradient
    android:angle="90"
    android:startColor="#FFFFFFFF"
    android:endColor="#FFCCCCCC"
    android:centerColor="#FFFFFFFF"
    android:centerY="0.9"
    android:type="linear"
    />

你必须设置android:centerColor,这种方式对我来说很好。