以编程方式生成的表不匹配父宽度

时间:2014-02-28 13:44:41

标签: android relativelayout tablerow android-tablelayout

我正在尝试动态生成我的活动布局但由于某种原因我无法使我的TableLayout或我的TableRow与父宽度匹配。我正在使用相对布局,然后创建我的TableLayout并在将我的TableLayout添加到RelativeLayout之前用行填充。

这是我的onCreate:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    context = this;

    RelativeLayout mainLayout = new RelativeLayout(context);
    RelativeLayout.LayoutParams relativeLayout = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT
    );
    mainLayout.setLayoutParams(relativeLayout);

    //Create the signature views
    //createPage(mainLayout);

    setupPage(mainLayout);

    setContentView(mainLayout);
}

这是我的setupPage()代码:

private void setupPage(RelativeLayout mainLayout)
{
    TableLayout mainTable = new TableLayout(context);
    RelativeLayout.LayoutParams tableLayoutParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT
    );
    mainLayout.setLayoutParams(tableLayoutParams);
    mainTable.setBackgroundResource(R.drawable.rectangle);

    //JOB DESCRIPTION title
    mainTable.addView(getRowTitle("JOB DESCRIPTION"));

    //----   END   ----
    mainLayout.addView(mainTable);
}

private TableRow getRowTitle(String text)
{
    TableRow row = new TableRow(context);
    TableLayout.LayoutParams rowLayout = new TableLayout.LayoutParams(
            TableLayout.LayoutParams.MATCH_PARENT,
            TableLayout.LayoutParams.MATCH_PARENT
    );
    row.setLayoutParams(rowLayout);
    row.setBackgroundResource(R.drawable.rectangle);//so i can see the outline of the row

    /*TextView title = new TextView(context);
    TableRow.LayoutParams editLayout = new TableRow.LayoutParams(
            TableRow.LayoutParams.WRAP_CONTENT,
            TableRow.LayoutParams.WRAP_CONTENT
    );
    editLayout.setMargins(15,0,0,0);
    title.setLayoutParams(editLayout);
    title.setText(text);

    row.addView(title);*/

    return row;
}

2 个答案:

答案 0 :(得分:3)

您没有在正确的视图上设置LayoutParams(最有可能以默认LayoutParams结尾)。在setupPage()方法中,您可以:

mainLayout.setLayoutParams(tableLayoutParams);

而不是在TableLayout

上设置它
mainTable.setLayoutParams(tableLayoutParams);

答案 1 :(得分:1)

试试这个 -

private void setupPage(RelativeLayout mainLayout)
{
TableLayout mainTable = new TableLayout(context);
RelativeLayout.LayoutParams tableLayoutParams = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.MATCH_PARENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT
);
mainTable.setLayoutParams(tableLayoutParams);
mainTable.setBackgroundResource(R.drawable.rectangle);

//JOB DESCRIPTION title
mainTable.addView(getRowTitle("JOB DESCRIPTION"));

//----   END   ----
mainLayout.addView(mainTable);
}