我正在努力学习如何编写Android程序,而且我很难弄清楚填充是如何工作的,特别是在TableLayout中的一个TableLayout中。
private void fillTable(int nrows, int ncols) {
final int CENTER = 0x11; // used for "gravity" parameters
TableLayout table = (TableLayout) this.findViewById(R.id.tablelayout);
int counter = 1;
TextView text;
for (int i = 0; i < nrows; i++) {
TableRow row = new TableRow(this);
table.addView(row);
for (int j = 0; j < ncols; j++) {
View cell;
text = new TextView(this);
text.setTextColor(Color.BLUE);
text.setText(Integer.toString(counter++));
text.setGravity(CENTER);
if (i == 2 && j == 2) {
FrameLayout frame = new FrameLayout(this);
text.setLayoutParams(new FrameLayout.LayoutParams(90, 45, CENTER));
frame.setPadding(0, 0, 0, 0);
frame.addView(text);
cell = frame;
} else {
cell = text;
}
cell.setBackgroundColor((i + j) % 2 == 0 ? Color.YELLOW : Color.WHITE);
row.addView(cell);
cell.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1F/ncols));
}
row.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1F/nrows));
}
}tablelayout看起来就像这样:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tablelayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TableLayout>我用nrows=12和ncols=5调用它。我在一个宽度为720像素的仿真器上运行。如果我将if (i==2&&j==2)更改为if (false),以便只显示一个TextView数组,那么正如我所预期的那样,这些列是均匀的。但是,使用编写的代码,中间列比其他列更宽。
我还尝试将android:stretchColumns="*"添加到tablelayout定义中,并从cell.setLayoutParams中删除权重参数,结果是相同的。
假设我有理由要为text.setLayoutParams指定像素(因为我计划稍后做什么),我如何获得相同的列宽?由于90*5很好地低于720,我不明白为什么,或哪里,额外的宽度被增加。
发布于 2014-02-19 00:22:14
无论何时处理权重,都必须让选项处理剩余的空间。在本例中,宽度。只需将每个元素的宽度设置为0:
cell.setLayoutParams(new TableRow.LayoutParams(0, LayoutParams.MATCH_PARENT, 1F/ncols));https://stackoverflow.com/questions/21866829
复制相似问题