【问题标题】:How to replicate a ViewGroup n times in another ViewGroup but with different values for Views?如何在另一个 ViewGroup 中复制 ViewGroup n 次,但 Views 具有不同的值?
【发布时间】:2019-08-15 11:29:27
【问题描述】:

我正在开发一个 Android 应用程序,我必须在其中创建一张卡片,其中包含多个 TextViewImageView。但是这些视图在卡片中被多次复制,带有不同的图像和文本(附图更好地总结了我的预期结果)。我想以编程方式为这些视图分配不同的图像和文本值。

一种解决方案是使用任何布局并用这些视图填充它,但它有太多的代码重复。另一种方法是为TextViewImageViewTextView 组合创建一个垂直的LinearLayout,并在我的父卡中使用<include>。但是我怎样才能使用这种方法通过 ID 访问子视图,以便以后以编程方式操作它们。以最少的代码重复设计这种布局的标准方法是什么?我希望有更好的出路。这是我的LinearLayout 的代码。

<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="@dimen/margin_parent">

    <TextView
            android:id="@+id/textview_whatever_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="4dp"/>

    <ImageView
            android:id="@+id/imageview_whatever"
            android:layout_width="@dimen/icon_height"
            android:layout_height="@dimen/icon_height"
            android:layout_marginBottom="4dp"/>

    <TextView
            android:id="@+id/textview_whatever_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

</LinearLayout>

这是我期望创建的结果。

【问题讨论】:

    标签: android xml android-layout android-viewgroup


    【解决方案1】:

    我认为最好的方法是使用 Include 方式,给 Includes 一个 ID

    <include
    android:id="@+id/whatever1"
    

    您可以参考项目

    whatever1.textview_whatever_1
    

    等等

    【讨论】:

    • 哦,好吧,它就像一个魅力!我不知道为什么这个想法从来没有出现在我的脑海中。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多