我有一个视图的布局-
<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>
我希望遍历我的数据模型,并将由第一个布局组成的多个视图注入到主布局中。我知道我可以通过在代码中完全构建控件来做到这一点,但我想知道是否有一种动态构建视图的方法,以便我可以继续使用布局,而不是将所有内容都放在代码中。
发布于 2011-06-02 23:30:42
使用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
等。
发布于 2011-06-02 23:33:03
请参见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);
发布于 2017-10-24 16:59:00
// Parent layout
LinearLayout parentLayout = (LinearLayout)findViewById(R.id.layout);
// Layout inflater
LayoutInflater layoutInflater = getLayoutInflater();
View view;
for (int i = 1; i < 101; i++){
// Add the text layout to the parent layout
view = layoutInflater.inflate(R.layout.text_layout, parentLayout, false);
// In order to get the view we have to use the new view with text_layout in it
TextView textView = (TextView)view.findViewById(R.id.text);
textView.setText("Row " + i);
// Add the text view to the parent layout
parentLayout.addView(textView);
}
https://stackoverflow.com/questions/6216547
复制相似问题