复杂的xml资源

时间:2023-03-09 22:04:01
复杂的xml资源

某些资源类型是由XML文件表示的多个复杂资源的组合。例子是一个animated vector drawable,它是一个封装了vector drawable和动画的drawable资源。这需要使用至少三个XML文件。

res/drawable/avd.xml

<?xml version="1.0" encoding="utf-8"?>
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/vectordrawable" >
    <target
        android:name="rotationGroup"
        android:animation="@anim/rotation" />
</animated-vector>

res/drawable/vectordrawable.xml

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="64dp"
    android:width="64dp"
    android:viewportHeight="600"
    android:viewportWidth="600" >

   <group
        android:name="rotationGroup"
        android:pivotX="300.0"
        android:pivotY="300.0"
        android:rotation="45.0" >
        <path
            android:fillColor="#000000"
            android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z" />

   </group>
</vector>

res/anim/rotation.xml

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/android"
    android:duration="6000"
    android:propertyName="rotation"
    android:valueFrom="0"

   android:valueTo="360" />

这么多文件只构成了一个animated vector drawable!如果vector drawable和animated在要别的地方重复使用,这是实现animated vector drawable的最佳方法。 如果它们只用于这个animated vector drawable,此外还有一种更简洁的方式来实现。

使用AAPT的内联资源格式,您可以在同一XML文件中定义所有三个资源。因为我们现在只构成一个animated vector drawable,我们将文件放在res/drawable/下。

res/drawable/avd.xml

<?xml version="1.0" encoding="utf-8"?>
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:aapt="http://schemas.android.com/aapt" >

    <aapt:attr name="android:drawable" >
        <vector
            android:height="64dp"
            android:width="64dp"
            android:viewportHeight="600"
            android:viewportWidth="600" >

           <group
                android:name="rotationGroup"
                android:pivotX="300.0"
                android:pivotY="300.0"
                android:rotation="45.0" >
                <path
                    android:fillColor="#000000"
                    android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z" />

           </group>
        </vector>
    </aapt:attr>

    <target android:name="rotationGroup">
        <aapt:attr name="android:animation" >
            <objectAnimator
                android:duration="6000"
                android:propertyName="rotation"
                android:valueFrom="0"

               android:valueTo="360" />
        </aapt:attr>
    </target>
</animated-vector>

XML的标记<aapt:attr>告诉AAPT标记的子标记应被当做资源并提取到其自己的资源文件中。 属性名的值指定在父标记中使用这个内联资源的位置。