Android矢量Drawable XML能否复用标签?有无类似<include/>的资源复用方案?
如何在Android Drawable XML中复用重复片段(类似布局)
好问题!布局里的<include>确实是复用的利器,但Drawable XML(包括矢量图和动画矢量图)里并没有完全对应的标签,不过我们有几个实用的方案来减少重复代码、优化资源体积,我给你一一说明:
1. 矢量图(Vector Drawable):用<use>标签复用路径/组
矢量图里的<use>标签就是专门用来复用已有元素的,它可以引用当前或其他矢量图里的path、group等元素的ID,完美解决重复绘制相同图形的问题。
举个例子:
首先创建一个包含重复元素的基础矢量图res/drawable/base_vector.xml:
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24"> <!-- 定义一个可复用的圆形路径 --> <path android:id="@+id/reusable_circle" android:fillColor="@color/black" android:pathData="M12,2a10,10 0 1,0 10,10A10,10 0 0,0 12,2Z"/> </vector>
然后在其他矢量图里引用这个圆形:
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24"> <!-- 引用base_vector里的圆形,还可以通过android:x/y调整位置 --> <use android:x="2" android:y="2" android:width="20" android:height="20" android:drawable="@drawable/base_vector" android:id="@+id/use_circle"/> <!-- 添加其他自定义元素 --> <path android:fillColor="@color/red" android:pathData="M12,6L12,18"/> </vector>
2. 动画矢量图(Animated Vector Drawable):复用动画片段
如果你的动画矢量图里有重复的动画逻辑,可以把这些动画单独抽出来放在res/animator文件夹里,然后在animated-vector的<target>标签里引用。
比如创建一个重复的旋转动画res/animator/rotate_anim.xml:
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android" android:propertyName="rotation" android:duration="1000" android:valueFrom="0" android:valueTo="360" android:repeatCount="infinite"/>
然后在动画矢量图里引用:
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/your_base_vector"> <target android:name="your_vector_group_id" android:animation="@animator/rotate_anim"/> </animated-vector>
3. 通用属性复用:使用资源引用
如果多个Drawable共享颜色、尺寸、圆角等属性,不要硬写具体值,而是把这些值定义在res/values/colors.xml、res/values/dimens.xml等资源文件里,然后用@color/xxx、@dimen/xxx引用。
比如:
<!-- 在colors.xml里定义 --> <color name="primary_color">#FF6200EE</color> <!-- 在多个Drawable里引用 --> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="@color/primary_color"/> <corners android:radius="@dimen/default_corner_radius"/> </shape>
4. 复杂场景:自定义Drawable类(代码层面复用)
如果你的重复逻辑比较复杂,XML层面的复用满足不了需求,可以考虑写一个自定义Drawable类,把重复的绘制逻辑封装进去,然后在XML里通过class属性引用这个自定义Drawable。
比如:
<drawable xmlns:android="http://schemas.android.com/apk/res/android" class="com.yourpackage.ReusableDrawable"/>
这样所有需要这个Drawable的地方都可以直接引用,不用重复写XML代码。
内容的提问来源于stack exchange,提问作者Ωmega
相关产品推荐
相关产品推荐

