【问题标题】:Adding a ViewGroup to a ViewGroup将视图组添加到视图组
【发布时间】:2011-12-08 17:48:10
【问题描述】:

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

main.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);
}

【问题讨论】:

    标签: android viewgroup


    【解决方案1】:

    当您执行findViewById(R.layout.secondlayout) 时,您正试图在设置内容视图之前找到一个视图。另外,secondlayout 不是视图的 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);
    

    【讨论】:

    • 这开始了,但我得到一个空白视图,只有标题
    • @Frazerm63 奇怪。发布您的onCreate 方法
    • 我假设上下文是:Context context = getBaseContext();
    • 不,只使用 Activity 上下文。您可以将其替换为this
    • 现在似乎可以工作了。玩弄 xml 布局似乎可以解决它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    相关资源
    最近更新 更多