在使用XML布局时,尝试将TextView动态添加到ScrollView时会崩溃

Mar*_*iek 7 android

这是一个非常简单的例子,我在R.layout.main中定义了一个ScrollView.然后我尝试动态添加TextView.

不幸的是这崩溃了.

ScrollView scroll = (ScrollView) this.findViewById(R.id.scrollView1);

TextView tv1 = new TextView(this);
tv1.setText("This is tv1");

scroll.addView(tv1);

setContentView(R.layout.main);
Run Code Online (Sandbox Code Playgroud)

现在我可以这样做:

ScrollView scroll = new ScrollView(this);
TextView tv1 = new TextView(this);
tv1.setText("This is tv1");

scroll.addView(tv1);

setContentView(scroll);
Run Code Online (Sandbox Code Playgroud)

但我真的希望能够在XML中定义一些基本UI元素,然后动态添加其他元素.

最好的方法是什么?

Oct*_*ean 11

那是因为您正在尝试访问尚未被Android解析的视图.

使用XML定义布局时,必须先调用,然后setContentView将布局文件引用传递给它,以便Android可以解析文件.只有这样你才能使用findViewById.

这基本上意味着您应该setContentView 尝试访问布局的任何元素之前调用它.