android - 将 ViewGroup 添加到 ViewGroup

标签 android viewgroup

我希望能够以编程方式将一个 View 组添加到另一个 View 组。两者都在 xml 中定义如下,连同我的 onCreate 方法:

主.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/firstll"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="first text" />

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="second text" />

secondlayout.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/secondll"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="first text" />

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="second text" />

创建时:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Context context = getBaseContext();

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.main, null);
    LinearLayout tv = (LinearLayout) inflater.inflate(R.layout.secondlayout, null);
    tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    ll.addView(tv);
    setContentView(ll);
}

最佳答案

当您执行 findViewById(R.layout.secondlayout) 时,您试图在设置内容 View 之前找到一个 View 。此外,secondlayout 不是 View 的 id,它是布局文件的名称和 id。

尝试做

LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.main, null);
LinearLayout tv = (LinearLayout) inflater.inflate(R.layout.secondlayout, null);
tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
ll.addView(tv);
setContentView(ll);

关于android - 将 ViewGroup 添加到 ViewGroup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8435294/

相关文章:

android - BroadcastReceiver 和 intent-filter?

android - 需要应用一种样式来摆脱 Entry 上的底线

android - Gradle-android apk创建后立即运行CustomTask

android - 是否可以将 ViewGroups 项目带到 ViewGroups sibling 的前面?

android - 在特定位置插入子项的自定义 ViewGroup

java - 如何为 Dagger 的类(与接口(interface))注入(inject)模拟

android - 如何在移动视觉条码扫描器上绘制叠加层?

android - 调用需要 API 级别 14(当前最小值为 8): android. view.ViewGroup#canScrollHorizo​​ntally

android - ScrollView 使自定义布局不可见

android - 在运行时从自定义 ViewGroup 中的 TextView 类型的子项获取 "getText()"