Android带边框表格的实现

时间:2024-01-06 08:55:20

最近做项目需要用到表格,数据是动态指定的,本来用GridView是很方便的,可是老大不同意用这么重量级的控件,想办法吧。

做表格很容易想到用TableLayout,那就自定义一个来搞。

一、表格最蛋疼的就是那根线,网上有个很好的方法,大概思路是这样的:

1、给表格设置一个背景色(线的颜色)

2、给表格设置一个内边距(线的宽度的一半)

3、设置每一项内边距(线的宽度的一半)

3、给项的内容设置一个背景色(颜色不同于线即可)

显示效果大概是这样的:

Android带边框表格的实现

二、数据的动态加载使用Adapter类,便与布局加载

自定义TableLayout加载的主体方法:

public void setAdapter(BaseAdapter baseAdapter, int column) {
    if (baseAdapter == null || baseAdapter.getCount() == 0) {
        return;
    }
    this.mAdapter = baseAdapter;
    this.column = column;
    drawLayout();
}
private void drawLayout() {
    removeAllViews();
    int realcount = mAdapter.getCount();
    int count = 0;
    if (realcount < column) {
        count = column;
    } else if (realcount % column != 0) {
        count = realcount + column - (realcount % column);
    } else {
        count = realcount;
    }
    TableRow tableRow = null;//每一行的TableRow
    for (int i = 0; i < count; i++) {
        final int index = i;
        View view = null;
        if (index >= realcount) {
        view = mAdapter.getView((realcount - 1), null, null);
        view.setVisibility(View.INVISIBLE);
        } else {
        view = mAdapter.getView(index, null, null);
        }
        if (index % column == 0) {// 整行
        tableRow = new TableRow(mContext);
        }
        if (tableRow != null) {//添加每一个Item
        tableRow.addView(view);
        }
        if (index % column == 0) {// 整行
        addView(tableRow, new TableLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        }
    }
}

三、使用和ListView的方式基本一样

public class MainActivity extends Activity {

    private List<Map<String, Object>> dataList;

    private TableBorderLayout layTable;

    private String[] datas = new String[] { "疯狂", "个性", "张扬", "抖擞", "加油", "奋斗",
        "努力", "精神" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      initViews();
      loadDatas();
    }

    private void initViews() {
      layTable = (TableBorderLayout) findViewById(R.id.layTable);
    }

    private void loadDatas() {
      dataList = new ArrayList<Map<String, Object>>();
      Map<String, Object> item = null;
      for (int i = 0; i < datas.length; i++) {
          item = new HashMap<String, Object>();
          item.put("Title", datas[i]);
          dataList.add(item);
      }
      layTable.setAdapter(new MyAdapter(this, dataList));
    }

}

感兴趣的可以去这个地址下载:https://github.com/PearLemon/TableBorderLayout.git