-1

我正在尝试使用表格布局以编程方式实例化一行按钮

    public class MainActivity extends Activity {
/** Called when the activity is first created. */
private final int gridSize = 3;
private TableRow rowArr[] = new TableRow[gridSize];
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    //Create the layout
    TableLayout MainLayout = new TableLayout(this);
    MainLayout.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.MATCH_PARENT));
    //MainLayout.setStretchAllColumns(true);

    for ( int i =0 ; i < gridSize ; i++){
        for(int j = 0; j < gridSize ; j++){

            Button button = new Button(this);
            button.setText(Integer.toString(i)+","+Integer.toString(j));
            rowArr[i].addView(button);

        }
        MainLayout.addView(rowArr[i]);
    }

//Set the view
    setContentView(MainLayout);
}

然而,这条线似乎抛出了一个空指针异常

     rowArr[i].addView(button);

我究竟做错了什么?

4

2 回答 2

2

TableRownull 因为你没有实例化它。尝试像这样实例化它 rowArr[i]=new TableRow();

for ( int i =0 ; i < gridSize ; i++){

    rowArr[i]=new TableRow();
        for(int j = 0; j < gridSize ; j++){

            Button button = new Button(this);
            button.setText(Integer.toString(i)+","+Integer.toString(j));
            rowArr[i].addView(button);

        }
        MainLayout.addView(rowArr[i]);
    }
于 2013-05-08T10:16:18.727 回答
2

您已经初始化了 rowArr 数组,但没有初始化它的单个 TableRow 元素。所以 rowArr[i] 将为空。在 for 循环中,将以下行放入其中:-

rowArr[i] = new TableRow(this);
于 2013-05-08T10:16:31.117 回答