我试图通过活动创建两个表格布局。 我已经有一个表格布局,但如何设置活动? 我知道要通过xml来做,但想以编程方式进行..
请帮助
答案 0 :(得分:1)
检查此answer和another example here
就像在xml中一样,您将创建一个TableLayout,提供参数并添加具有您自己的UI的行。
答案 1 :(得分:1)
在xml中使用一个线性布局(或相对布局)通过活动的onCreate()方法中的findViewById()获取它的引用。之后动态创建表并将其添加到线性布局。我创建一个方法这样做 。前 -
LinearLayout linear= (LinearLayout ) findViewById(R.id.linear);
//call method to add the tablelayout.
linear.addView(createtable(3,5));
private TableLayout createtable(int requiredcolumn, int requiredrow) {
TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT, 1f);
TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f);
//for border
rowParams.setMargins(2, 2, 2, 2);
TableRow.LayoutParams itemParams = new TableRow.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f);
TableLayout tableLayout = new TableLayout(MainActivity.this);
tableLayout.setLayoutParams(tableParams);
tableLayout.setBackgroundColor(Color.WHITE);
for (int row = 0; row < requiredrow; row++) {
TableRow tableRow = new TableRow(MainActivity.this);
tableRow.setLayoutParams(rowParams);
for (int column = 0; column < requiredcolumn; column++) {
Random color = new Random();
int randomColor = Color.argb(255, color.nextInt(256),
color.nextInt(256), color.nextInt(256));
TextView textView = new TextView(MainActivity.this);
textView.setLayoutParams(itemParams);
textView.setBackgroundColor(randomColor);
tableRow.addView(textView);
}
tableLayout.addView(tableRow);
}
return tableLayout;
}