0

我无法在运行时向我的活动的主布局添加子布局。更准确地说,当我调用setContentView(layout)layout.add(mySubLayout)时,我得到一个空指针异常,其中布局由findViewById(R.id.idLay)检索。下面是xml代码。

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/idLay"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true"
    tools:context=".TrainingActy" >

似乎不可能修改静态创建的布局。但是我看到堆栈溢出的答案似乎可以做我想做的事,而且我从来没有在 android 的文档中读过关于不可能做到这一点的任何内容。

4

3 回答 3

1

资源 不能在运行时修改。但是您可以使用充气器来获取布局视图,然后将视图添加到该布局。

于 2013-07-11T08:49:07.127 回答
1

无论布局是如何创建的,都可以在运行时修改布局。这是一个如何做到这一点的例子。我假设在此示例中您发布的布局位于 file 中main.xml

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ViewGroup main = (ViewGroup) findViewById(R.id.idLay);
    TextView text = new TextView(this);
    text.setText("This is a test!");
    main.addView(text);
}

当然,这不会修改您的资源文件,因此当您下次对其进行扩充时,您必须再次运行它完成所有步骤。

于 2013-07-11T09:08:20.613 回答
0

findViewById(id) 返回一个视图,而 Layouts 是一个视图组。

我建议用您的布局编写另一个 XML。然后按照您的描述包含它:

mainLayout.add(R.layout.your_custom_layout);
于 2013-07-11T08:50:55.120 回答