Android layout 向布局动态添加组件

Android layout 向布局动态添加组件,android-layout,android-view,Android Layout,Android View,晚上好,我正在尝试将按钮添加到现有布局中…在阅读了其他一些答案后,我尝试了以下方法: public void addButton(View v) { Button cb=new Button(this); try { LinearLayout l= (LinearLayout) findViewById(R.layout.main); //cb.setLayoutParams( new LinearLayout.LayoutParam

晚上好,我正在尝试将按钮添加到现有布局中…在阅读了其他一些答案后,我尝试了以下方法:

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.
-将
替换为您在XML中为LinearLayout指定的id(行
android:id=“@+id/…”
)。

!!!你在开玩笑吧?它的作用很简单:’)你不知道我花了多少时间在这上面。非常感谢:)我想投票支持你的答案,但我不能(需要15个声誉)