【问题标题】:How to add table rows to table layout programmatically? [duplicate]如何以编程方式将表格行添加到表格布局? [复制]
【发布时间】:2017-04-11 19:23:48
【问题描述】:

您好,我正在尝试将一些 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);
}
}

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

【问题讨论】:

    标签: android tablelayout


    【解决方案1】:

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

    setContentView(R.layout.activity_main);
    

    【讨论】:

    • 非常感谢!现在可以了
    • 太好了,投票并接受答案:)
    • 我接受了答案,也投了赞成票,但因为我还没有足够的声誉,所以不会公开显示赞成票
    猜你喜欢
    • 2023-03-15
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多