添加组件动态地布局
问题描述:
晚上好,我想简单的添加按钮到一个现有的布局......读了一些别人的答案后,我尝试这样做:添加组件动态地布局
public void addButton(View v)
{
Button cb=new Button(this);
try {
LinearLayout l= (LinearLayout) findViewById(R.layout.main);
//cb.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
l.addView(cb,new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
} catch (Exception e) {
Log.d("EXCEPTION", e.getMessage(),e.getCause());
e.printStackTrace();
}
}
然后我得到一个空指针异常,因为如下:
03-01 22:34:03.967: W/System.err(7047): java.lang.NullPointerException
03-01 22:34:03.967: W/System.err(7047): at custom.component.app.CustomComponentActivity.addButton(CustomComponentActivity.java:49)
03-01 22:34:03.967: W/System.err(7047): at java.lang.reflect.Method.invokeNative(Native Method)
03-01 22:34:03.967: W/System.err(7047): at java.lang.reflect.Method.invoke(Method.java:511)
谁能告诉我是什么,我甚至没有使用线程
答
它是由线路原因引起:?
LinearLayout l= (LinearLayout) findViewById(R.layout.main)
findViewById()
用于在布局中查找视图。您错误地使用了R.layout.main
。将R.layout.main
更改为R.id.<linearlayout>
- 用您在XML中提供LinearLayout的标识替换<linearlayout>
(行android:id="@+id/..."
)。
哇! 你在开玩笑吗? 它很简单:') 你不知道我在这花了多少时间。 谢谢你:)))) – 2013-03-04 12:09:04
我想为你的答案投票,但我不能(需要15个声望) – 2013-03-04 12:10:13