代码: public abstract class GroupBaseAdapter extends BaseAdapter { @Override public final int getCount() { // TODO Auto-generated method stub int count = 0; int len = getSectionCount(); for (int i = 0; i < len; i++) { count = 1 + getRowCount(i) + count; } return count; } @Override public final Object getItem(int position) { // TODO Auto-generated method stub Object object = null; IndexPath indexPath = getIndexPath(position); if (indexPath.getRow() == -1){ object = getGroupItem(indexPath.getSection()); }else { object = getRowItem(indexPath.getRow(), indexPath.getSection()); } return object; } @Override public final long getItemId(int position) { // TODO Auto-generated method stub long id = 0; IndexPath indexPath = getIndexPath(position); if (indexPath.getRow() == -1){ id = getGroupItemId(indexPath.getSection()); }else { id = getRowItemId(indexPath.getRow(), indexPath.getSection()); } return id; } @Override public final View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View view = null; IndexPath indexPath = getIndexPath(position); if (indexPath.getRow() == -1){ //group header view = getSectionView(indexPath.getSection(), convertView, parent); }else{ view = getRowView(indexPath.getRow(), indexPath.getSection(), convertView, parent); } return view; } private IndexPath getIndexPath(int position){ Log.d("tag", "position = " + position); //判断position section = ? row = ? int section = 0; int pos = 1 + getRowCount(0); while (section < getSectionCount()) { if (position == 0) return new IndexPath(-1, 0); if (pos > position) { // group row int row = position - (pos - getRowCount(section)); return new IndexPath(row, section); } else if (pos == position) { // group header return new IndexPath(-1, section + 1); } pos = pos + 1 + getRowCount(++ section); } return null; } /** * ListView IndexPath * */ public static class IndexPath { private int row; private int section; public IndexPath(int row, int section) { super(); this.row = row; this.section = section; } public int getRow() { return row; } public int getSection() { return section; } } /** * 在子类中实现这些方法 * */ public Object getRowItem(int row, int section){ return null; } public long getRowItemId(int row, int section){ return 0; } public Object getGroupItem(int section){ return null; } public long getGroupItemId(int section){ return 0; } public abstract int getSectionCount(); public abstract int getRowCount(int section); public abstract View getSectionView(int section, View convertView, ViewGroup parent); public abstract View getRowView(int row, int section, View convertView, ViewGroup parent); } 继承这个Adapter,和BaseAdapter一样使用。 | 项目中需要用到分组列表,数据为动态,APIDemo中的例子不能满足要求。而ExpandListView存在收起时才能刷新的问题(项目要求不能收起),虽然实现了,但是很不爽。最后自己实现了一个。section(组头) row(组所属行)
ListView 分组完美实现
最新推荐文章于 2017-07-04 11:14:22 发布