2

这段代码对我不起作用。我进行了调试,我认为错误来自 setlayoutparams 但它没有意义,因为如果我取出 for 循环并只创建 1 个按钮(而不是按钮数组),那么它将起作用。

   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
4

2 回答 2

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]);
}
于 2012-08-14T17:52:02.537 回答
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]);
    }
于 2013-04-25T03:06:06.477 回答