兩個單元格合併成一個單元格顯示的效果如下圖所示:
如何實現上面的效果:
1.得到TableLayout。
2.用第一步得到的TableLayout調用下面的方法:
private void appendTable(TableLayout tableLayout) {
int size = fileList.size();
int columnNum = 4;
boolean isSpanCell = false;
boolean startNewRow = true;
boolean endOfOneRow = false;
table.setPadding(10, 0, 5, 0);
//得到TableLayout所在的Fragment的寬度,
int width = fragment.getView().getWidth();
TableRow row = null;
for (int j = 0; j < size; j++) {
// TODO 下面紅色的代碼是我定義的兩個相鄰的單元格合併的規則,你可以根據定義自己的合併規則.
if (j % columnNum == 0) {
startNewRow = true;
}
else {
startNewRow = false;
}
if (j % columnNum == 3 || j == size - 1) {
endOfOneRow = true;
}
else {
endOfOneRow = false;
}
if (j % 5 == 0 || (j + 2) % 20 == 0) {
isSpanCell = true;
}
else {
isSpanCell = false;
}
if (startNewRow) {
row = new TableRow(this.context);
}
View cell = generateCell(j, isSpanCell, width);
//當前行增加新生成的單元格
row.addView(cell);
//如果一行結束,tableLayout 把當前行添加上。
if (endOfOneRow) {
row.setPadding(0, 0, 0, 10);
tableLayout.addView(row);
}
}
}
3.第二步綠色的方法如下所示:
private View generateCell(int index, boolean isSpanRow,int width) {
ViewHolder holder = new ViewHolder();
View view = null;
view = inflater.inflate(R.layout.file_item, null);
TableRow.LayoutParams tlp = new TableRow.LayoutParams();
tlp.span = 2;// TableRow.LayoutParams,設置跨兩列
LinearLayout layout = new LinearLayout(context);
holder.fileCreatorIcon = (ImageView) view
.findViewById(R.id.file_creator_icon);
holder.fileGridViewItemLayout = (RelativeLayout) view
.findViewById(R.id.file_gridview_item_relativelayout);
holder.fileUpdatedTime = (TextView) view
.findViewById(R.id.file_upload_time);
holder.fileOwnerName = (TextView) view.findViewById(R.id.file_text_owner);
holder.fileName = (TextView) view.findViewById(R.id.file_name);
layout.setPadding(0, 0, 10, 0);
//根據是否跨列來決定當前單元格的寬度,根據當前Fragment的寬度來動態計算。
if (isSpanRow) {
layout.addView(view, (width - 40) / 5 * 2 + 10, 150);
layout.setLayoutParams(tlp);
}
else {
layout.addView(view, (width - 40) / 5, 150);
}
//顯示當個Item的方法,可以根據自己的情況實現
showFileInfo(holder, index, view);
return layout;
}