我需要在我的应用中动态地将一些表格添加到linearlayout。我写这段代码:
LinearLayout tabella = (LinearLayout) findViewById(R.id.tabella_contatori);
for(int i =0; i<array_list.size(); i++){
TableRow row = new TableRow(getApplicationContext());
row.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
TextView data = new TextView(getApplicationContext());
data.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0.2f));
data.setTextAppearance(getApplicationContext(), android.R.attr.textAppearanceMedium);
data.setTextColor(Color.BLACK);
data.setBackgroundColor(Color.WHITE);
data.setPadding(2, 0, 0, 0);
data.setText("asd");
row.addView(data);
tabella.addView(row);
}
}
但是当我打开应用程序时,没有任何意外。我已经检查了array_list.size是否大于0。 我能怎么做? 谢谢,马蒂亚
答案 0 :(得分:3)
问题出在TextView布局参数中。类型应该是TableRow.LayoutParams而不是LinearLayout.LayoutParams。
data.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
答案 1 :(得分:1)
获取表格布局并尝试在main.xml中使用它...
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myTableLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:text="Some Text"/>
</TableRow>
</TableLayout>
在你的活动中
this.setContentView(R.layout.main);
/* Find Tablelayout defined in main.xml */
TableLayout tl = (TableLayout)findViewById(R.id.myTableLayout);
/* Create a new row to be added. */
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
/* Create a TextView to be the row-content. */
TextView data = new TextView(getApplicationContext());
data.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 0.2f));
data.setTextAppearance(getApplicationContext(), android.R.attr.textAppearanceMedium);
data.setTextColor(Color.BLACK);
data.setBackgroundColor(Color.WHITE);
data.setPadding(2, 0, 0, 0);
data.setText("asd");
/* Add TextView to row. */
tr.addView(data);
/* Add row to TableLayout. */
tl.addView(tr,new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));