【发布时间】:2014-11-25 13:46:27
【问题描述】:
例如,如果我有这样的空布局:
layout1.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
还有一些类似这样的布局:
layout2.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView 1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 3"
android:layout_weight="1"/>
</LinearLayout>
我想以编程方式将layout2.xml 添加到layout1.xml。我需要有多个不同的版本layout2.xml,我会在需要时添加它们。每个人在TextView 和Buttons 上都有不同的文字。
如果是普通的 Android View,我通常会像这样使用 addView:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv1 = new TextView(this);
tv1.setText("HELLO");
my_linear_layout.addView(tv1);
Button btn2 = new Button(this);
bt2.setText("WORLD");
my_linear_layout.addView(btn2);
}
如果我没有像 TextView 或 Button 这样简单的东西,并且如果我定义了自己的 XML View,我该怎么办?
是否有可能以某种方式将所有视图放入适配器中,例如 ListView,然后在需要时获取它,然后在那些 Views 上调用 addView?
【问题讨论】:
-
使用 LayoutInflator 执行此操作请参阅 stackoverflow.com/questions/2335813/…
标签: android xml android-layout android-custom-view