使用layout_weight参数在不同行中对齐Textview

时间:2011-08-03 08:00:54

标签: android android-layout

我想在列表视图中显示航班列表。我想让他们所有人都对齐。我使用了LinearLayout,有重力和填充。但是我想减少第4列的空间,所以我可以做更大的文本大小。我试图将此元素的layout_weight设置为0,其余所有设置为1.但它不起作用。到目前为止我有这个

Table of flight boards

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

如果您要将ListViewLinearLayout视图列表一起使用(我会将TableRow列表放入TableLayout),那么我会建议以总空间的百分比预定义每列的宽度(即,您将允许列分配多少屏幕)。行间的一些事情:

// basically you build your adapter here
LinearLayout.LayoutParams wrapWrapLinearLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int[] columnWidths = new int[]{20, 20, 20, 20, 20};

ArrayList<LinearLayout> tableRows = new ArrayList<LinearLayout>();//this is the adapter
LinearLayout row = new LinearLayout(this);
//add a header
row.setLayoutParams(wrapWrapLinearLayoutParams);
row.setGravity(Gravity.CENTER);
row.setBackgroundColor(headerColor);
row.addView(makeTableRowWithText(headerForCol1, columnWidths[0]));
row.addView(makeTableRowWithText(headerForCol2, columnWidths[1]));
row.addView(makeTableRowWithText(headerForCol3, columnWidths[2]));
row.addView(makeTableRowWithText(headerForCol4, columnWidths[3]));
row.addView(makeTableRowWithText(headerForCol5, columnWidths[4]));
tableRows.add(row);
for(int i = 0; i < numberOfItemsInTheFlightsTable; i++) {
    row = new LinearLayout(this);
    row.setLayoutParams(wrapWrapLinearLayoutParams);
    row.setGravity(Gravity.CENTER);
    row.addView(makeTableRowWithText(col1Text, columnWidths[0]));
    row.addView(makeTableRowWithText(col2Text, columnWidths[1]));
    row.addView(makeTableRowWithText(col3Text, columnWidths[2]));
    row.addView(makeTableRowWithText(col4Text, columnWidths[3]));
    row.addView(makeTableRowWithText(col5Text, columnWidths[4]));
    tableRows.add(row);
}

//util method
private TextView recyclableTextView;

public TextView makeTableRowWithText(String text, int widthInPercentOfScreenWidth) {
    int screenWidth = getResources().getDisplayMetrics().widthPixels;
    recyclableTextView = new TextView(this);
    recyclableTextView.setText(text);
    recyclableTextView.setTextColor(Color.BLACK);
    recyclableTextView.setTextSize(20);
    recyclableTextView.setWidth(widthInPercentOfScreenWidth * screenWidth / 100);
    return recyclableTextView;
}

我的意思是,诀窍是你预定义了每列分配的屏幕百分比。

答案 1 :(得分:0)

执行以下操作

LinearLayout LL1包含前4列

LinearLayout LL2包含最后一列

RelativeLayout RL包含LL1LL2

您现在可以将LL2放在容器右侧

<强> EDITED