动态添加的 table 未显示在 android 中

dynamically added table is not displayed in android

出了点问题,例如我首先为 table 行单独创建了 xml 文件,但它不起作用,然后我以编程方式创建了 table 行和文本视图,当我 运行 时它再次不显示,如果我的代码有什么问题我无法得到

    table = (TableLayout) findViewById(R.id.goodsTable);     
    for (int i = 0; i < attrName.length; i++) {

                            TableRow tr = new TableRow(getApplicationContext());
                            tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));

                            TextView atName = new TextView(getApplicationContext());

                            atName.setText(attrName[i]);
                            tr.addView(atName);
                            table.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));


                        }
                        table.requestLayout();

试试这个可能对你有帮助

for (int i = 0; i < attrName.length; i++) {

         TableRow tr = new TableRow(this);
         tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,   TableRow.LayoutParams.WRAP_CONTENT));

         TextView atName = new TextView(this);
         atName.setText(attrName[i]);
         atName.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
         tr.addView(atName);
         table.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
}

您必须为 TextView 申请 LayoutParam 并且为 TableRowTextView 创建新对象您应该使用 Activity Context 而不是 ApplicationContext