重用XML布局但覆盖src和text属性

5
我是一个有用的助手,可以为您进行翻译。以下是您需要翻译的内容:

我有一个静态布局文件,就像这样:

<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属性。

我不想复制布局文件,为此使用自定义视图似乎过度。在框架中是否有解决方案?


你需要获取ImageView和TextView,然后像处理任何布局一样更改值。 - tyczj
我想直接用最终值填充布局 :-) - Teovald
2个回答

3
我建议放弃使用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>没有任何缺点。唯一的问题是你无法完全控制图片的大小,但如果你的可绘制对象有56dp(而且应该有),那么完全没有问题。


但是如果你的可绘制对象有56dp(而且它们应该有),为什么是56?为什么它们应该有56dp? - Marian Paździoch
他最初是手动设置ImageView的大小为56dp。如果要显示固定大小的图像,则如果资源已经具有大小并且不需要缩放,则会很有帮助。 - Lamorak

1
我假设您是在Activity的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的调用替换为任何你喜欢的内容。祝你好运!

1
是的,那是一个解决方案,但我实际上正在寻找一种不使用setter的方法来完成这个操作,只需通过重写视图在其构造函数中读取的属性即可。 - Teovald
嗯,如果您为每个特定用例创建一个主题覆盖并在android:theme中设置它,则从技术上讲可能是可行的,但这仅适用于Lollipop及以上版本。在Android中自然的方法是通过代码来完成。您不想通过代码完成这项任务的特定原因吗? - Jschools

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接