如何通过添加另一个视图以编程方式添加到XML?

时间:2016-02-25 23:13:12

标签: android xml programmatically-created

我正在制作一款与Reddit / YouTube / Yahoo News应用程序类似的应用程序,它使用API​​来收集有关最近帖子的信息。

启动应用时,它会显示所有最近的帖子:

http://wpuploads.appadvice.com/wp-content/uploads/2014/07/screen1136x1136-68-576x1024.jpeg

目标是使所有帖子符合match_parent宽度和wrap_content高度(最大300 dp高度),并且 - 就像上面链接的图片一样 - 使所有帖子符合一个外观;顶部的标题,中间的正文/图片以及下面的评论数量。

让我们说我常见的View布局是这样的:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:layout_marginTop="8dp"
    android:layout_marginBottom="8dp"
    android:background="#ffffff"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Lesson 1"
        android:textAllCaps="false"
        android:textColor="#8c8c8c"
        android:textSize="40dp"
        android:gravity="center_horizontal"/>

    <ImageButton
        android:id="@+id/imageButton1"
        android:background="@drawable/lesson1"
        android:layout_width="250dp"
        android:layout_height="150dp"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:layout_marginLeft="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="10 Comments"
        android:textColor="#000000"/>

    </LinearLayout>

我想在每次有新帖子时复制此布局样式(文本,图像,文本)并将其添加到现有XML。我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用LayoutInflater将xml文件扩展为View。然后,您可以将该视图添加到任何您想要的布局。