Android tablet Fragment 中 TableLayout的同一行相邻的两个单元格合并成一个单元格显示?

两个单元格合并成一个单元格显示的效果如下图所示:


如何实现上面的效果:

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;
  }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章