2013-03-01 132 views
0

晚上好,我想簡單的添加按鈕到一個現有的佈局......讀了一些別人的答案後,我嘗試這樣做:添加組件動態地佈局

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) 

誰能告訴我是什麼,我甚至沒有使用線程

回答

0

它是由線路原因引起:?

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

findViewById()用於在佈局中查找視圖。您錯誤地使用了R.layout.main。將R.layout.main更改爲R.id.<linearlayout> - 用您在XML中提供LinearLayout的標識替換<linearlayout>(行android:id="@+id/...")。

+0

哇! 你在開玩笑嗎? 它很簡單:') 你不知道我在這花了多少時間。 謝謝你:)))) – 2013-03-04 12:09:04

+0

我想爲你的答案投票,但我不能(需要15個聲望) – 2013-03-04 12:10:13