Android 使用ExpandableListView打造可展开列表组件

在项目中要用到,需要实现的效果如下:

1、可遍历1-12个月份。

2、可查看每个月份下对应的照片。


运行效果如下:


Android 使用ExpandableListView打造可展开列表组件_第1张图片

实现思路:

一开始打算使用ScrollView嵌套一个LinearLayout,然后add进不同子项,不过这样写代码量会比较多,而且要做子项点击事件处理,逻辑会稍微复杂一点。最后使用了ExpandableListView组件,将数据全部抽离出来,依次填进去就搞好了,十分方便,在此记录一下。


代码步骤:

1、首先是布局文件: newphoto_layout.xml




    

    


2、初始化组件:

    ExpandableListView eblv_newphoto;
        eblv_newphoto = (ExpandableListView) findViewById(R.id.eblv_newphoto);
  MyExpandableListAdapter adapter = new MyExpandableListAdapter(data);
        eblv_newphoto.setAdapter(adapter);
3、编写MyExpandableListAdapter类:

  public class MyExpandableListAdapter implements ExpandableListAdapter {
        String[] monthEnames = {"一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"};
        List mdata;
        String[] colors = {"#B36AE1","#c62817","#022550",
                "#118730","#1167bd","#560809",
                "#f4d23e","#56a9f6","#f18f2e",
                "#3b214c","#ea5e5b","#72be49"
        };

        public MyExpandableListAdapter(List data ) {
            this.mdata = data;
        }


        @Override
        public void registerDataSetObserver(DataSetObserver observer) {

        }

        @Override
        public void unregisterDataSetObserver(DataSetObserver observer) {

        }

        @Override
        public int getGroupCount() {
            return monthEnames.length;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            int num = 0;
            for (int i = 0;i tempChildlist = new ArrayList<>();
            List resultChildlist = new ArrayList<>();

            //得到该月份下所有的PhotoPicture
            for (int i = 0;i resultChildlist = (List) getChild(groupPosition,childPosition);

            if (resultChildlist.size() ==1) {
                NGImageloadHelper.displayImage(img1,Config.IMG_AUDIO_PATH +resultChildlist.get(0).getPath());
            } else if (resultChildlist.size() ==2) {
                NGImageloadHelper.displayImage(img2,Config.IMG_AUDIO_PATH +resultChildlist.get(1).getPath());

            }

            return item_photorv;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        @Override
        public boolean areAllItemsEnabled() {
            return false;
        }

        @Override
        public boolean isEmpty() {
            return false;
        }

        @Override
        public void onGroupExpanded(int groupPosition) {

        }

        @Override
        public void onGroupCollapsed(int groupPosition) {

        }

        @Override
        public long getCombinedChildId(long groupId, long childId) {
            return 0;
        }

        @Override
        public long getCombinedGroupId(long groupId) {
            return 0;
        }

    }






你可能感兴趣的:(Android,Android进阶学习笔记)