android - 重用 xml 布局但覆盖 src 和文本属性

标签 android android-layout

我有一个静态布局文件,假设是这样的:

<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/

相关文章:

android - YouTubePlayerView 在屏幕旋转时停止

android - 向多个 Android 设备发送推送通知时,如何检测哪些特定设备已卸载该应用程序?

android - 如何在android xml中绘制三角形

android - Native Android -> 如何创建自定义弯曲底部导航

java - 火力地堡 : App crash when notification comes with app not opened

android - 更改背景android标题栏

java - java 中的正则表达式和 ISO-8859-1 字符集

android - 提高布局性能

android - picasso 什么时候刷新图像缓存

android - getFragmentManager().beginTransaction() 问题