2012-08-14 45 views
2

該代碼塊對我無效。我調試了,我認爲錯誤來自setlayoutparams,但它沒有任何意義,因爲如果我取出for循環並創建一個按鈕(而不是一個按鈕數組),那麼它會工作。無法以編程方式創建按鈕陣列而沒有錯誤

Button btn[] = new Button[oNumber]; 
    for (int i=0;i<oNumber;i++){ 
     btn[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT)); 
     btn[i].setText(oName[i]); 
     System.out.println("making b's"); 
     layout.addView(btn[i]); 
    } 

這是我得到的錯誤。我確實有清單中正確寫入的活動。

08-14 12:45:56.482: E/AndroidRuntime(4060): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rcontrol/com.example.rcontrol.ViewTarget}: java.lang.NullPointerException 
+0

按照azgolfer的步驟。 它解決了您的問題 – 2012-08-14 17:59:04

回答

10

您創建的按鈕的排列,但並沒有將其初始化:更多詳細

Button btn[] = new Button[oNumber]; 
for (int i=0;i<oNumber;i++){ 
    btn[i] = new Button(this); // initialize it 
    btn[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT)); 
    btn[i].setText(oName[i]); 
    System.out.println("making b's"); 
    layout.addView(btn[i]); 
} 
+0

感謝它的工作。 – zms6445 2012-08-14 18:02:21

1

int oNumber = 4;

String oName[] = {"x","2","3","4"}; 
    Button btn[] = new Button[oNumber]; 
    LinearLayout layout = (LinearLayout) findViewById(R.id.layout1); 

    for (int i=0;i<oNumber;i++){ 
     btn[i] = new Button(this); // initialize it 
     btn[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT)); 
     btn[i].setText(oName[i]); 
     btn[i].setOnClickListener(this); 
     System.out.println("making b's"); 
     layout.addView(btn[i]); 
    } 
相關問題