我可以在一个 Drawable XML 中使用多个渐变吗?

Bug*_*der 2 android

目前我有 3 个可绘制的 XML 文件,定义了 3 个单独的渐变。这些渐变在我的代码中动态设置为 imageView 的背景颜色(工作正常)。

示例:drawable\morningsky.xml

<?xml version="1.0" encoding="utf-8"?>
<item android:bottom="4dp">
  <shape>
     <gradient
        android:startColor="@color/blue"
        android:endColor="@color/dark_blue"
        android:angle="270" />
  </shape>
Run Code Online (Sandbox Code Playgroud)

示例:drawable\eveningsky.xml

<?xml version="1.0" encoding="utf-8"?>
<item android:bottom="4dp">
  <shape>
     <gradient
        android:startColor="@color/orange"
        android:endColor="@color/yellow"
        android:angle="270" />
  </shape>
Run Code Online (Sandbox Code Playgroud)

我以这种方式在我的 imageView 中设置背景:

iv.setBackgroundResource(R.drawable.morningsky);
Run Code Online (Sandbox Code Playgroud)

一切都很好,但我真的需要为每个渐变使用多个不同的可绘制资源文件吗?有什么方法可以在一个可绘制文件中定义所有渐变,然后从我的代码中加载该渐变?

小智 6

你可以使用这样的东西

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">
            <gradient
                android:type="radial"
                android:gradientRadius="300"
                android:startColor="@android:color/white"
                android:endColor="@android:color/transparent"
                android:centerX="0.25"
                android:centerY="0.5"/>
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <gradient
                android:type="radial"
                android:gradientRadius="300"
                android:startColor="@android:color/white"
                android:endColor="@android:color/transparent"
                android:centerX="0.75"
                android:centerY="0.5"/>
        </shape>
    </item>
</layer-list>
Run Code Online (Sandbox Code Playgroud)