android中没有显示动态添加的表

时间:2016-06-13 10:09:10

标签: android android-tablelayout tablerow

出现了问题,首先我为表行创建了单独的xml文件,它没有工作,然后我以编程方式创建了表行和文本视图,再次在运行时不显示,我无法获取我的代码有什么问题

    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();

1 个答案:

答案 0 :(得分:2)

试试这可能会对你有所帮助

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));
}

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