无法以编程方式创建按钮数组而不会出现错误

时间:2012-08-14 17:49:03

标签: android arrays button nullpointerexception

这段代码对我不起作用。我调试了,我认为错误来自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

2 个答案:

答案 0 :(得分: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]);
}

答案 1 :(得分:1)

了解更多细节。

在Number = 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]);
    }