【问题标题】:Dynamically load customized table cells in table在表格中动态加载自定义表格单元格
【发布时间】:2010-08-19 09:10:19
【问题描述】:

我想在表格中创建 5 种不同类型的单元格以及标识符,并根据类型根据给定数据适当地加载它们? 在 TableLayout 中创建 TableRow 似乎是其中一种选择,但是如何根据类型动态创建 tableRows?

提前感谢。

【问题讨论】:

    标签: android tablerow


    【解决方案1】:

    你能检测出执行时间的类型吗?如果是,则应该直接使用 switch 或 if else 结构。

    根据行类型在运行时扩展 XML 资源:

    ((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE))
    .inflate(layoutId, yourTableLayout, true);
    

    在膨胀资源之前设置适当的layoutId,然后继续。 yourTableLayouttrue 参数只是我的猜测,请查看LayoutInflater 的文档并选择适合您需要的充气方法。

    要动态创建 TableRows,本教程可能会有所帮助:Creating TableRow rows inside a TableLayout programatically

    基本上:

    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));
    

    似乎简单快捷,我还没有测试过。

    【讨论】:

    • 由于tableRows属于不同的类型[5种不同的类型],所以添加的元素是不同的。我想用一些标识符将它保存在 xml 中,并在运行时加载适当的标识符。有可能吗?
    • 我已经更新了答案,希望能澄清你的问题。
    猜你喜欢
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多