【问题标题】:Add xml dynamically to layout动态添加xml到布局
【发布时间】:2014-01-25 15:43:06
【问题描述】:

我有一个(复杂的)RelativeLayout,其中包含一些 TextView、ImageView 和一个按钮。创建此布局的频率取决于数据库中的数据。我从列表中获取这些数据并想动态显示它,我该怎么办?

要动态添加的xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/zusatz_content" >

<TextView
    android:id="@+id/text1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="20dp"
    android:layout_marginRight="15dp"
    android:layout_marginLeft="15dp"
    android:text="Lorem Ipsum 1" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/text2"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="20dp"
    android:text="@string/button_desc" />

<ImageView
    android:id="@+id/image"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/text1"
    android:layout_centerHorizontal="true"
    android:contentDescription="@string/ima_zusatz_desc"
    android:src="@drawable/nix" />

<TextView
    android:id="@+id/text2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/text1"
    android:layout_below="@+id/image"
    android:text="Lorem Ipsum 2" />

注意:文本和图像应根据数据库中的内容动态更改。

谢谢,汤姆

【问题讨论】:

  • 不清楚你在问什么。
  • 如何以编程方式将这些 xml 布局添加到父布局

标签: java android xml android-layout


【解决方案1】:

除了您的 XML,您还需要一个适配器和某种 ListView。在您的适配器中,您必须实现

public View getView(int position, View convertView, ViewGroup parent)

在此方法中,返回您的新视图(可能使用 LayoutInflator 和您的 xml 创建)并更新显示在每个按钮/文本视图上的数据。

请务必研究 convertView 的工作原理。如果您的列表很长,那么正确使用 convertView 对性能的提升是巨大的。如果你没弄错,Android 的 listview 和 baseadpater 将为你完成艰苦的工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多