【问题标题】:dynamically added table is not displayed in android动态添加的表在android中不显示
【发布时间】:2016-06-13 18:18:48
【问题描述】:

出了点问题,首先我为表格行单独创建了 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();

【问题讨论】:

  • 这是我上面提到的代码,使用 xml 文件 TableRow row = (TableRow) LayoutInflater.from(getApplicationContext()).inflate(R.layout.attribute_row, table, false); ((TextView) row.findViewById(R.id.attributeName)).setText(attrName[i]); ((TextView) row.findViewById(R.id.attributeValue)).setText(barcode); table.addView(row, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));

标签: android android-tablelayout tablerow


【解决方案1】:

试试这个可能对你有帮助

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

【讨论】:

  • 当我使用 'this' 而不是 'getApplicationContext()' 时,它会出错,我想注意我的代码在 searchButton.setOnClickListener 中
  • 使用YourActivityName.this
  • 非常感谢@ahishek,你让我过得愉快,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-08
  • 2012-11-20
  • 1970-01-01
  • 2022-10-18
  • 1970-01-01
  • 2023-03-24
相关资源
最近更新 更多