我有一些可绘制资源,这些资源仅在单个xml布局中使用。我想将它们插入到特定的xml布局(内联)中,这样我可以更好地组织我的文件,并减少重载的drawable文件夹
我找到了这个主题:https://developer.android.com/guide/topics/resources/complex-xml-resources
但是使用内联可绘制资源作为另一个资源...我想在布局xml中使用它
示例:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/round_corner"
android:orientation="horizontal"
android:padding="@dimen/smallMargin">
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:drawableTop="@drawable/code"
android:text="@string/delete"
/>
</androidx.appcompat.widget.LinearLayoutCompat>
其中code.xml是:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:width="@dimen/popupButtonSize"
android:height="@dimen/popupButtonSize"
android:drawable="@drawable/ic_population" />
</layer-list>
代码仅在该特定布局中使用,有什么方法可以使其内联?
您不能在同一个xml文件中,但是您可以将可绘制对象和大小直接分配给视图,而不是使用layer-list
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/buttonDelete"
android:layout_width="@dimen/popupButtonSize"
android:layout_height="@dimen/popupButtonSize"
android:layout_gravity="bottom"
android:drawableTop="@drawable/ic_population"
android:text="@string/delete" />
似乎是什么问题?如果您按照指南进行操作,则不会出现问题:
xmlns:aapt="http://schemas.android.com/aapt"
添加到根节点android:drawableTop="@drawable/code"
子元素替换aapt:attr
属性>最终XML将如下所示:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/round_corner"
android:orientation="horizontal"
android:padding="@dimen/smallMargin">
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="@string/delete">
<aapt:attr name="android:drawableTop">
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:width="@dimen/popupButtonSize"
android:height="@dimen/popupButtonSize"
android:drawable="@drawable/ic_population" />
</layer-list>
</aapt:attr>
</androidx.appcompat.widget.AppCompatButton>
</androidx.appcompat.widget.LinearLayoutCompat>