我想在表格中创建 5 种不同类型的单元格以及标识符,并根据类型根据给定数据适当地加载它们?在 TableLayout 中创建 TableRow 似乎是其中一种选择,但是如何根据类型动态创建 tableRows?
提前谢谢。
你能检测到执行时间的类型吗?如果是,则应该直接使用 switch 或 if else 结构。
要根据行类型在运行时扩展 XML 资源,请使用:
((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(layoutId, yourTableLayout, true);
在膨胀资源之前设置适当的layoutId,然后继续。参数yourTableLayout和true只是我的猜测,请查看LayoutInflater的文档并选择适合您需要的 inflate 方法。
要动态创建 TableRows,本教程可能会有所帮助:以编程方式在 TableLayout 中创建 TableRow 行
基本上:
1- 获取 TableLayout 并创建 TableRow
// Get the TableLayout
TableLayout tl = (TableLayout) findViewById(R.id.maintable);
TableRow tr = new TableRow(this);
tr.setId(100+current);
tr.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
2-创建要添加的元素
TextView labelTV = new TextView(this);
labelTV.setId(200+current);
labelTV.setText(provinces[current]);
labelTV.setTextColor(Color.BLACK);
labelTV.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
tr.addView(labelTV);
3- 将 TableRow 添加到 TableLayout
// Add the TableRow to the TableLayout
tl.addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
似乎简单快捷,我还没有测试过。