最近做了一个有关android 列表分组显示的问题,我在网上查了很多资料,基本上的思路都是一样的,但是感觉都存在一个问题,就是当数据量过大的时候,会存在内存溢出的问题.
@Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; //根据标签类型加载不通的布局模板 if(listTag.contains(getItem(position))){ //如果是标签项 view = LayoutInflater.from(getContext()).inflate(R.layout.group_list_item_tag, null); }else{ //否则就是数据项了 view = LayoutInflater.from(getContext()).inflate(R.layout.group_list_item, null); } //显示名称 TextView textView = (TextView) view.findViewById(R.id.group_list_item_text); textView.setText(getItem(position)); //返回重写的view return view; }
大概思路就是,要Tag的集合,并进行判断,每一个tag组会存成一个相应的Item,在Adapter进行判断,但是这样会频繁的加载view布局,造成内存溢出,我也尝试了一下,解决办法,就是在getView方法里进行相应的判断,但是感觉不太有效,也可能是我的方法有问题,希望看到好的解决办法。 但是在此我找到一个自己感觉比较好的解决办法,就是ExpandableListView,在这里把方法呈现给大家 ,希望有所帮助,首先我会把所有需要的数据,存成一个分组的集合,很简单,算法如下 :
定义一个集合:
private Map<String,List<Person>> mapList = new HashMap<String,List<Person>>();
List<Person> personList = 后台获取的集合;
for(Person person:personList){ String dateString = DateUtils.dateToString(getApplicationContext(),board.getDateTime()); if(mapList.containsKey(dateString)){ mapList.get(dateString).add(person); }else{ List<Person> tempBoard = new ArrayList<Person>(); tempBoard.add(board); mapList.put(dateString, tempBoard); } }
在定义一个adapter
public class StationboardSearchAdapter extends BaseExpandableListAdapter{ private Context context; private ExpandableListView listView; private LayoutInflater inflater; private Map<String,List<Person>> mapList; public StationboardSearchAdapter(Context context,Map<String,List<Person>> mapList,ExpandableListView listView){ this.context = context; this.listView = listView; this.mapList = mapList; this.inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getGroupCount() { return mapList.keySet().size(); } public int getChildrenCount(int groupPosition) { return mapList.get(mapList.keySet().toArray()[groupPosition]).size(); } public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { if(convertView == null) convertView = inflater.inflate( layout, null); ...... ..... } public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if(convertView == null) convertView = inflater.inflate( R.layout.**, null); ...... ...... return convertView; } public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } public Object getGroup(int groupPosition) { return null; } public Object getChild(int groupPosition, int childPosition) { return null; } public long getGroupId(int groupPosition) { return 0; } public long getChildId(int groupPosition, int childPosition) { return 0; } public boolean hasStableIds() { return false; } @Override public void onGroupCollapsed(int groupPosition) { super.onGroupCollapsed(groupPosition); this.listView.expandGroup(groupPosition); } }