如何以编程方式将表行添加到表布局



嗨,我正在尝试将一些 TableRows 添加到 TableLayout 中,TableLayout 是在 xml 文件中声明的,TableRows 仅在 java 代码中初始化。虽然有一些类似的问题,但我无法让它在我的代码中工作:

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TableLayout;
    import android.widget.TableRow;
    import android.widget.TableRow.LayoutParams;
    public class MainActivity extends Activity {
    TableLayout tableLayout;
    Button[][] buttons =new Button[9][9];
    TableRow tableRow[]=new TableRow[9];
    TableRow.LayoutParams layoutParams=new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    tableLayout = (TableLayout) findViewById(R.id.tablay);
    for(int line=0; line<9; line++){
        tableRow[line]=new TableRow(this);
        tableRow[line].setLayoutParams(layoutParams);
        tableRow[line].setVisibility(View.VISIBLE);
    }
    for(int line=0; line<9; line++){
        for(int col=0; col<9; col++){
            buttons[line][col]=new Button(this);
            buttons[line][col].setText(""+line+col);
            buttons[line][col].setLayoutParams(layoutParams);
            buttons[line][col].setVisibility(View.VISIBLE);
            tableRow[line].addView(buttons[line][col]);
        }
    }
    for(int i=0; i<9; i++){
        tableLayout.addView(tableRow[i], new TableLayout.LayoutParams(
                LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
}
setContentView(R.layout.activity_main);
}
}

该应用程序总是在启动后立即终止,我看不出问题是什么。感谢您的帮助!

在super.onCreate(savedInstanceState(之后移动以下行;

setContentView(R.layout.activity_main);

最新更新