动态地将视图添加到视图中

我有一个视图的布局 -

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0px"
    android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_header"
        style="@style/Home.ListHeader" />

    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_none"
        android:visibility="gone"
        style="@style/TextBlock"
        android:paddingLeft="6px" />

    <ListView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_list" />


</LinearLayout>

我想要做的是在我的主要活动中使用这样的布局

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0px"
    android:id="@+id/item_wrapper">
</LinearLayout>

我想循环访问我的数据模型,并将包含第一个布局的多个视图注入到主布局中。 我知道我可以通过在代码中完全构建控件来做到这一点,但我想知道是否有办法动态构建视图,以便我可以继续使用布局,而不是将所有内容都放在代码中。


使用LayoutInflater根据您的布局模板创建视图,然后将其注入到您需要的视图中。

LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.your_layout, null);

// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");

// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

您可能需要调整要插入视图的索引。

此外,根据您希望它适合父视图的方式设置LayoutParams。 例如FILL_PARENTMATCH_PARENT等。


请参阅LayoutInflater类。

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup parent = (ViewGroup)findViewById(R.id.where_you_want_to_insert);
inflater.inflate(R.layout.the_child_view, parent);

它看起来像你真正想要一个带有自定义适配器的ListView来扩展指定的布局。 使用ArrayAdapter和方法notifyDataSetChanged()您可以完全控制Views的生成和呈现。

看看这些教程

  • http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
  • http://developerlife.com/tutorials/?p=327
  • http://www.androidguys.com/2008/07/14/fancy-listviews-part-one/
  • 链接地址: http://www.djcxy.com/p/84741.html

    上一篇: Dynamically Add Views into View

    下一篇: What's the difference between fill