代码之家  ›  专栏  ›  技术社区  ›  Prabhat

android表格布局的动态创建

  •  3
  • Prabhat  · 技术社区  · 14 年前

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

    我已经创建了一个带有width fill\u parent的行布局,textView位于最左侧,imageView位于最右侧。但是,当我运行这个程序时,行宽度显示为wrap\u content,而不是用图像重叠文本填充父对象。请帮忙。谢谢

    1 回复  |  直到 14 年前
        1
  •  1
  •   gtcompscientist    13 年前

    我注意到的第一件事是在添加视图时没有设置任何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);
    }