Android 重用xml布局,但覆盖src和文本属性

Android 重用xml布局,但覆盖src和文本属性,android,android-layout,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:lay

我有一个静态布局文件,比如:

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

我希望能够在整个应用程序中多次重用此布局文件,但根据每个用例更改text&src属性


我不想复制布局文件,为它定制一个视图似乎有些过分。框架中是否有解决方案?

我假设您正在活动的
onCreate()
中扩展此布局。布局膨胀后,您需要在代码中获得对ImageView和TextView的引用,然后可以对它们调用方法

首先,向ImageView添加一个id:
android:id=“@+id/image

然后,在Java代码中:

@Override
public void onCreate(Bundle savedInstanceState) {
    // inflate the layout
    setContentView(R.layout.your_layout);

    // get references
    ImageView imageView = (ImageView) findViewById(R.id.image);
    TextView textView = (TextView) findViewById(R.id.placeholder_error_info);

    // set properties
    imageView.setImageResource(R.drawable.some_drawable);
    textView.setText("something");
}

您可以用任何您喜欢的方式替换对setImageResource和setText的调用。祝您好运!

我将放弃
线性布局的概念–您可以轻松地使用
文本视图

将所有全局属性移动到样式

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

与AFAIK相比,这没有任何缺点。唯一的问题是你不能完全控制图像大小,但是如果你的可绘制图像有56dp(而且应该是56dp)你很好。

你需要获得ImageView和TextView,然后像更改任何布局一样更改值。我想用最终值直接膨胀布局:-)是的,这是一个解决方案,但我实际上正在寻找一种不使用setter的方法,只需覆盖中视图读取的属性即可它的构造器。嗯,我想如果你为每个特定用例创建一个主题覆盖,并在
android:theme
中设置它,技术上是可能的,但这只适用于棒棒糖和更高版本。在android中实现这一点的自然方式是通过代码。你不想通过代码实现这一点有什么特别的原因吗?”但是,如果您的绘图设备有56dp(而且它们应该)“为什么是56,为什么它们应该呢?他最初是手动将
ImageView
大小设置为56dp。如果您想显示固定大小的图像,如果资源已经有了大小,这会很有帮助。并且不需要进行缩放。
<TextView
    style="@style/TextWithImage"
    android:drawableTop="@drawable/some_drawable"
    android:text="something" />