【问题标题】:Dynamic creation of tablelayout android动态创建tablelayout android
【发布时间】:2011-04-19 08:24:02
【问题描述】:

我想动态地将行添加到表格布局中。这是我的代码。

 TableRow tableRow = null;
 TextView textView = null;
 ImageView imageView = null;
 TableLayout tableLayout = (TableLayout)findViewById(R.id.tableLayout);
 RelativeLayout relativeLayout = null;
         for (String string: listOfStrings) {
                            tableRow = new TableRow(this);
                            relativeLayout = (RelativeLayout) View.inflate(this,
                                    R.layout.row, null);
                            textView = (TextView) relativeLayout.getChildAt(0);
                            textView.setText(string);
                            imageView= (ImageView) relativeLayout.getChildAt(1);
                            imageView.setBackgroundColor(R.color.blue);
                            tableRow.addView(relativeLayout);
                            tableLayout.addView(tableRow);
                        }

我创建了一个宽度为 fill_parent 的行布局,最左侧的 textView 和最右侧的 imageView。然而,当我运行这个程序时,行宽出现 wrap_content 而不是 fill_parent 与图像重叠文本。请帮忙。谢谢

【问题讨论】:

    标签: android


    【解决方案1】:

    我注意到的第一件事是您在添加视图时没有设置任何 LayoutParams。

    TableRow tableRow = null;
    TextView textView = null;
    ImageView imageView = null;
    TableLayout tableLayout = (TableLayout)findViewById(R.id.tableLayout);
    RelativeLayout relativeLayout = null;
    
    for (String string: listOfStrings)
    {
        tableRow = new TableRow(this);
        relativeLayout = (RelativeLayout) View.inflate(this, R.layout.row, null);
        textView = (TextView) relativeLayout.getChildAt(0);
        textView.setText(string);
        imageView= (ImageView) relativeLayout.getChildAt(1);
        imageView.setBackgroundColor(R.color.blue);
    
        //Here's where I would add the parameters...
        TableLayout.LayoutParams rlParams = new TableLayout.LayoutParams(FILL_PARENT, WRAP_CONTENT);
        tableRow.addView(relativeLayout, rlParams);
        tableLayout.addView(tableRow);
    }
    

    在实践中,我也会将行的创建抽象到它们自己的方法中。简化使用/重用。

    【讨论】:

      猜你喜欢
      • 2016-01-10
      • 2012-04-26
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-04
      • 1970-01-01
      相关资源
      最近更新 更多