某些資源類型是由多個複雜資源組成,以 XML 檔案的形式呈現。其中一個例子是動畫向量可繪項目,這個可繪製資源封裝了一個向量可繪項目和一個動畫。這需要使用至少三個 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 版本相容。