使用BaseExpandableListAdapter 可以实现所谓的可折叠的列表,例如QQ里好友的分组的功能。
BaseExpandableListAdapter与BaseAdapter的基本原理是一样的,只不过在传入list的时候,要传入两组,一组是groupArray ,一组时childArray,前者用于组名(类似QQ的好友、同学、朋友),后者的每个元素都是一组子数据(类似QQ同学中的张三,李四的集合),实现adapter
public class ExpandableAdapter extends BaseExpandableListAdapter{ private LinkedList<TeacherSumGroupsModel> groupArray; private List<LinkedList<TeacherSumGroupDetailModel>> childArray; private Context context; private LayoutInflater inflater; public ExpandableAdapter(Context context,LinkedList<TeacherSumGroupsModel> courseGroupList, List<LinkedList<TeacherSumGroupDetailModel>> childArray){ inflater = ((Activity) context).getLayoutInflater(); this.groupArray = courseGroupList; this.childArray = childArray; } public int getGroupCount() { // TODO Auto-generated method stub return groupArray.size(); } public int getChildrenCount(int groupPosition) { // TODO Auto-generated method stub return childArray.get(groupPosition).size(); } public Object getGroup(int groupPosition) { // TODO Auto-generated method stub return groupArray.get(groupPosition); } public Object getChild(int groupPosition, int childPosition) { // TODO Auto-generated method stub return childArray.get(groupPosition).get(childPosition); } public long getGroupId(int groupPosition) { // TODO Auto-generated method stub return groupPosition; } public long getChildId(int groupPosition, int childPosition) { // TODO Auto-generated method stub return childPosition; } public boolean hasStableIds() { // TODO Auto-generated method stub return false; } public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { // TODO Auto-generated method stub TextView title; if(convertView == null){ convertView = inflater.inflate(R.layout.simple_listview_item, parent, false); } title = (TextView) convertView.findViewById(R.id.simple_listview_textview); String t = " "+groupArray.get(groupPosition).getname(); title.setText(t); return convertView; } public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { // TODO Auto-generated method stub TextView title; if(convertView == null){ convertView = inflater.inflate(R.layout.simple_listview_item, parent, false); } title = (TextView) convertView.findViewById(R.id.simple_listview_textview); String account = childArray.get(groupPosition).get(childPosition).getAccount(); String name = childArray.get(groupPosition).get(childPosition).getName(); String t = account +" "+name; Log.e("sumlist", "info is " +t); title.setText(t); return convertView; } public boolean isChildSelectable(int groupPosition, int childPosition) { // TODO Auto-generated method stub return true; } }
代码摘自现在的某个项目。
类似与BaseAdapter的关键getView方法,这里比较重要的是getGroupView和getChildView方法,其实内部实现都是类似的。