最近作項目須要用到表格,數據是動態指定的,原本用GridView是很方便的,但是老大不一樣意用這麼重量級的控件,想辦法吧。git
作表格很容易想到用TableLayout,那就自定義一個來搞。github
1、表格最蛋疼的就是那根線,網上有個很好的方法,大概思路是這樣的:ide
一、給表格設置一個背景色(線的顏色)佈局
二、給表格設置一個內邊距(線的寬度的一半)this
三、設置每一項內邊距(線的寬度的一半)spa
三、給項的內容設置一個背景色(顏色不一樣於線便可)code
顯示效果大概是這樣的:blog
2、數據的動態加載使用Adapter類,便與佈局加載rem
自定義TableLayout加載的主體方法:get
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)); } } }
3、使用和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