Android - 将视图动态添加到视图中 [英] Android - Dynamically Add Views into View
问题描述
我有一个视图布局 -
I have a layout for a view -
<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>
我想做的是在我的主要活动中使用这样的布局
What I want to do, is in my main activity with a layout like this
<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>
我想遍历我的数据模型并将包含第一个布局的多个视图注入到主布局中.我知道我可以通过完全在代码中构建控件来做到这一点,但我想知道是否有一种方法可以动态构建视图,以便我可以继续使用布局而不是将所有内容都放在代码中.
I want to loop through my data model and inject multiple views consisting of the first layout into the main layout. I know I can do this by building the controls completely within the code, but I was wondering if there was a way to dynamically build the views so that I can continue using a layout instead of putting everything in code.
推荐答案
使用LayoutInflater
根据你的布局模板创建一个视图,然后将它注入到你需要的视图中.
Use the LayoutInflater
to create a view based on your layout template, and then inject it into the view where you need it.
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));
您可能需要调整要插入视图的索引.
You may have to adjust the index where you want to insert the view.
此外,根据您希望它适合父视图的方式设置 LayoutParams.例如用 FILL_PARENT
或 MATCH_PARENT
等
Additionally, set the LayoutParams according to how you would like it to fit in the parent view. e.g. with FILL_PARENT
, or MATCH_PARENT
, etc.
这篇关于Android - 将视图动态添加到视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!