0
我在學習如何編寫Android程序,而且我無法弄清楚填充的工作方式,特別是在TableLayout
內的FrameLayout
中。在TableLayout中使用FrameLayout時不理解額外填充
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,我不明白爲什麼或者在哪裏增加了額外的寬度。
好的,這似乎工作。謝謝!我想我誤解了一些「TableLayout」和/或「TableRow」的文檔。 – ajb
你似乎並不相信。以下是LinearLayout的一個簡要說明。我相信這同樣適用於實現它的任何佈局: 「要創建線性佈局,其中每個小孩在屏幕上使用相同的空間量,請將每個視圖的android:layout_height設置爲」0dp「(對於垂直佈局)或每個視圖的android:layout_width設置爲「0dp」(對於水平佈局),然後將每個視圖的android:layout_weight設置爲「1」。 http://developer.android.com/guide/topics/ui/layout/linear.html#Weight – Toguard