我正在以编程方式尝试在Android中为我的表格布局添加视图。但我无法在我的行中添加超过1个视图。它只渲染第一个视图。第二列是空的。我的代码如下。
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TableRow tr1 = new TableRow(this);
TableRow tr2 = new TableRow(this);
TextView productNumber = new TextView(this);
productNumber.setText("PRODUCT NUMBER: " + b[0].getProduct_id());
productNumber.setTextSize(18);
productNumber.setTextColor(Color.RED);
productNumber.setPadding(20, 5, 20, 5);
tr1.addView(productNumber);
TextView productDesc = new TextView(this);
productDesc.setText("PRODUCT DESCRIPTION: " + b[0].getItem_description());
productDesc.setTextSize(18);
productDesc.setTextColor(Color.RED);
productDesc.setPadding(20, 5, 20, 5);
tr2.addView(productDesc);
productNumber.setLayoutParams(lp);
productDesc.setLayoutParams(lp);
tl.setStretchAllColumns(true);
tl.addView(tr1, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
tl.addView(tr2, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
for (ProductBean p: b) {
TableRow lineSeparator = new TableRow(this.getApplicationContext());
View line = new View(this.getApplicationContext());
line.setMinimumHeight(1);
line.setBackgroundColor(Color.WHITE);
line.setPadding(0, 5, 0, 5);
lineSeparator.addView(line);
tl.addView(lineSeparator);
Set<String> headers = p.getAttr().keySet();
//Till here it works fine. The following code seems to not add more than 1 view
for (String s: headers) {
Log.i("S", "S: " + p.getAttr().get(s));
TableRow tableRow = new TableRow(getApplicationContext());
TextView textView = new TextView(getApplicationContext());
textView.setText(s);
textView.setPadding(20, 5, 20, 5);
textView.setTextSize(15);
tableRow.addView(textView);
textView = new TextView(getApplicationContext());
textView.setText(p.getAttr().get(s));
textView.setPadding(20, 5, 20, 5);
textView.setTextSize(15);
tableRow.addView(textView); //This view is not rendered.
tl.addView(tableRow);
}
}
但是,我在单独的活动和布局中尝试了以下操作,并且它成功运行。你好是一栏,另一栏是世界。
for (int i=0; i<5; i++) {
TableRow tableRow = new TableRow(getApplicationContext());
TextView textView = new TextView(getApplicationContext());
textView.setText("Hello");
tableRow.addView(textView);
textView = new TextView(getApplicationContext());
textView.setText("World");
tableRow.addView(textView);
tableLayout.addView(tableRow);
}
为什么我的代码不会渲染第二个视图呢?我能够记录两个textview的内容,但它不会渲染行中的第二个视图。请帮忙。我完全迷失了,现在已经在我的头上打了12个小时!!
答案 0 :(得分:0)
我也想到了问题和解决方案。实际上我的xml只有一个滚动视图和一个表格布局。我添加的前两个文本视图,然后是我添加的表格行,将跨越整个屏幕的宽度,因此表格的第一列将占据屏幕的整个宽度。
tl.addView(tr1, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
tl.addView(tr2, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
现在我在滚动视图外创建了一个单独的LinearLayout,并将上面这两行的内容添加到LinearLayout中。工作正常!