内嵌复杂的 XML 资源
某些资源类型是由 XML 文件表示的多个复杂资源合成的。例如动画矢量可绘制对象就是封装矢量可绘制对象和动画的可绘制资源。这需要使用至少 3 个 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" />
这里使用了很多文件,目的只是为了合成一个动画矢量可绘制对象!如果该矢量可绘制对象和动画会在别处重复使用,这是实现动画矢量可绘制对象的最佳方式。如果这些文件只是用于合成该动画矢量可绘制对象,那么有一种更为紧凑的方式来实现它们。
使用 AAPT 的内嵌资源格式,您可以在同一 XML 文件中定义所有三种资源。由于我们正在合成一个动画矢量可绘制对象,因此我们将该文件放在 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,该标记的子标记应被视为资源并提取到其自己的资源文件中。属性名称中的值用于指定在父标记内使用内嵌资源的位置。
AAPT 会为所有内嵌资源生成资源文件和名称。使用此内嵌格式构建的应用可与所有版本的 Android 兼容。
网友评论