将组件动态添加到布局中

时间:2013-03-01 21:00:43

标签: 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.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)

谁能告诉我那是什么?我甚至没有使用线程

1 个答案:

答案 0 :(得分:0)

这是由线路引起的:

LinearLayout l= (LinearLayout) findViewById(R.layout.main)

findViewById()用于在布局中查找视图。您错误地使用了R.layout.main。将R.layout.main更改为R.id.<linearlayout> - 将<linearlayout>替换为您在XML中为其提供LinearLayout的ID(行android:id="@+id/...")。

相关问题