Android - ビューにビューを動的に追加する 質問する

Android - ビューにビューを動的に追加する 質問する

ビューのレイアウトがあります -

<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>

データ モデルをループし、最初のレイアウトで構成される複数のビューをメイン レイアウトに挿入したいと考えています。コントロールを完全にコード内で構築することでこれを実現できることはわかっていますが、すべてをコード内に配置する代わりにレイアウトを引き続き使用できるように、ビューを動的に構築する方法があるかどうか疑問に思っています。

ベストアンサー1

使用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_PARENT、 、MATCH_PARENT、 などを使用します。

おすすめ記事