gpt4 book ai didi

android - 将 ViewGroup 添加到 ViewGroup

转载 作者:行者123 更新时间:2023-11-29 02:09:09 28 4
gpt4 key购买 nike

我希望能够以编程方式将一个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com