使用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方法,其實內部實現都是類似的。