我有一个静态布局文件,假设是这样的:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="24dp"
android:src="@drawable/some_drawable" />
<TextView
android:id="@id/placeholder_error_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="something"
/>
</LinearLayout>
我希望能够在我的应用程序中多次重用这个布局文件,但根据每个用例更改文本和 src 属性。
我不想复制布局文件,为此自定义 View 似乎有些矫枉过正。框架中有解决方案吗?
最佳答案
我会放弃 LinearLayout
概念 – 您可以轻松使用 TextView
仅。
将所有全局属性移动到样式
<style name="TextWithImage">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">match_parent</item>
<item name="android:drawablePadding">24dp</item>
</style>
在你的布局中使用这个 TextView
具有覆盖文本和可绘制对象
<TextView
style="@style/TextWithImage"
android:drawableTop="@drawable/some_drawable"
android:text="something" />
与<include>
相比没有任何缺点AFAIK。唯一的问题是您无法完全控制图像大小,但如果您的可绘制对象具有 56dp(它们应该),您就完全没问题。
关于android - 重用 xml 布局但覆盖 src 和文本属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31167511/