Android在開發中的實用技巧之ExpandableListView簡單實現商品列表折疊

根據已上線的app里總結出來的實用小技巧

一、簡介

在日常開發,有可能會遇到需要一些可以展開的列表,比如QQ的好友列表。但是,用Android的該怎么做呢?其實在我沒有接觸過ExpandableListView類之前,都是自定義控件繼承于ListView或者ListView嵌套ListView來實現的, 當然也不推薦大家這樣使用, 這樣使用會降低app頁面的加載速度和性能. 然后,后來發現了Android也給我們提供了ExpandableListView類,完美實現這樣類似的需求, 極大的方便了我們開發.

二、使用

  • 開發工具:
  • Android Studio
  • 使用的第三方框架:

Demo來自某個線上電商app的頁面, 使用前先看看效果圖


example.gif
  • activity_main.xml

使用AppBarLayout 來作為標題, 是因為有陰影效果, 看著還不錯
<com.zhy.autolayout.AutoLinearLayout/>是一個實現第三方適配的控件
ExpandableListView里的android:groupIndicator="@null"功能是去除掉默認的關閉和打開狀態的圖片(系統默認的不好看)

<com.zhy.autolayout.AutoLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.zhy.autolayout.AutoLinearLayout
            android:id="@+id/ll_title_root"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#ec0f38"
            android:orientation="vertical">

            <com.zhy.autolayout.AutoFrameLayout
                android:layout_width="match_parent"
                android:layout_height="88px">

                <TextView
                    android:id="@+id/tv_title"
                    android:layout_width="wrap_content"
                    android:layout_height="fill_parent"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="優惠套餐"
                    android:textColor="#ffffff"
                    android:textSize="32px" />

                <com.zhy.autolayout.AutoLinearLayout
                    android:id="@+id/ll_back"
                    android:layout_width="100px"
                    android:layout_height="match_parent"
                    android:clickable="true"
                    android:gravity="center">

                    <ImageView
                        android:id="@+id/iv_back"
                        android:layout_width="44px"
                        android:layout_height="44px"
                        android:layout_gravity="center_vertical"
                        android:src="@mipmap/icon_back" />
                </com.zhy.autolayout.AutoLinearLayout>
            </com.zhy.autolayout.AutoFrameLayout>
        </com.zhy.autolayout.AutoLinearLayout>
    </android.support.design.widget.AppBarLayout>

    <ExpandableListView
        android:id="@+id/elv_collocation"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#eeeff3"
        android:divider="#eeeff3"
        android:dividerHeight="0dp"
        android:groupIndicator="@null"
        android:listSelector="@null" />
</com.zhy.autolayout.AutoLinearLayout>
  • MainActivity.java

初始化數據
elv_collocation.expandGroup(0);默認展開第一個

public class MainActivity extends AppCompatActivity {
    private ExpandableListView elv_collocation;
    private List<CollocationPackageBean> collocationList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        elv_collocation = (ExpandableListView) findViewById(R.id.elv_collocation);
        initData();
    }

    private void initData() {
        collocationList = new ArrayList<>();
        CollocationPackageBean collocation_1 = new CollocationPackageBean();
        CollocationPackageBean collocation_2 = new CollocationPackageBean();

        collocation_1.setTotalPrice(new BigDecimal(897));
        collocation_1.setDiscountFee(new BigDecimal(20));
        collocation_1.setName("818國貨套餐3");
        List<CollocationPackageBean.CollocationSkuBean> goodsList_1 = new ArrayList<>();
        goodsList_1.add(new CollocationPackageBean.CollocationSkuBean("Meizu/魅族 魅藍 note3 全網通 手機 銀白 16GB", "http://img11.hqbcdn.com/product/07/0a/070ac7abd57c6d9251d89547f3d62501.jpg"));
        goodsList_1.add(new CollocationPackageBean.CollocationSkuBean("VR PLUS 智能眼鏡vr虛擬現實頭盔 3D沉浸式 暴風魔鏡 vr plus 智能頭盔 白色", "http://img15.hqbcdn.com/product/c6/10/c610075082199955a8d5dcf2aa765b17.jpg"));
        collocation_1.setCollocationSkuDoList(goodsList_1);

        collocation_2.setTotalPrice(new BigDecimal(1034));
        collocation_2.setDiscountFee(new BigDecimal(26));
        collocation_2.setName("超值套餐");
        List<CollocationPackageBean.CollocationSkuBean> goodsList_2 = new ArrayList<>();
        goodsList_2.add(new CollocationPackageBean.CollocationSkuBean("Meizu/魅族 魅藍 note3 全網通 手機 銀白 16GB", "http://img11.hqbcdn.com/product/07/0a/070ac7abd57c6d9251d89547f3d62501.jpg"));
        goodsList_2.add(new CollocationPackageBean.CollocationSkuBean("Uka/優加 Meizu/魅族 魅藍 note3全覆蓋全屏鋼化玻璃膜 白色", "http://img8.hqbcdn.com/product/9c/15/9c15571aa92905ea1edafb0a288f1ebb.jpg"));
        goodsList_2.add(new CollocationPackageBean.CollocationSkuBean("SanDisk/閃迪 至尊高速MicroSDHC-TF移動存儲卡 Class10-48MB/S 升級版 16G", "http://img14.hqbcdn.com/product/29/cd/29cda69f5036b38454b6592f96fde774.jpg"));
        goodsList_2.add(new CollocationPackageBean.CollocationSkuBean("Huawei/華為 AM116 金屬耳機 三鍵線控耳機 尊爵版", "http://img9.hqbcdn.com/product/0a/90/0a905d9988c91fb0625d9ee44377c8e0.jpg"));
        goodsList_2.add(new CollocationPackageBean.CollocationSkuBean("Lesimo/梵簡 初見系列10000毫安充電寶 手機平板通用 移動電源 黑色", "http://img11.hqbcdn.com/product/67/3a/673ac0343758ce64e97c2d9986cbbef3.jpg"));
        collocation_2.setCollocationSkuDoList(goodsList_2);

        collocationList.add(collocation_1);
        collocationList.add(collocation_2);
        elv_collocation.setAdapter(new CollocationListAdapter(this, elv_collocation, collocationList));
        elv_collocation.expandGroup(0);
    }
}
  • CollocationListAdapter.java

ExpandableListView的適配器需要繼承自該控件特有的適配器BaseExpandableListAdapter

public class CollocationListAdapter extends BaseExpandableListAdapter {
    private LayoutInflater inflater;
    private Context context;
    private ExpandableListView elv_collocation;
    private List<CollocationPackageBean> data;

    public CollocationListAdapter(Context context, ExpandableListView elv_collocation, List<CollocationPackageBean> data) {
        this.context = context;
        this.elv_collocation = elv_collocation;
        this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.data = data;
    }

    @Override
    public int getGroupCount() {
        return data.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return data.get(groupPosition).getCollocationSkuDoList().size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return data.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return data.get(groupPosition).getCollocationSkuDoList().get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;//如果子條目需要響應click事件,必需返回true
    }

    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        ParentViewHolder parentViewHolder;
        if (null == convertView) {
            convertView = inflater.inflate(R.layout.collocation_list_item_parent, parent, false);
            parentViewHolder = new ParentViewHolder(convertView);
            convertView.setTag(parentViewHolder);
            AutoUtils.auto(convertView);
        } else {
            parentViewHolder = (ParentViewHolder) convertView.getTag();
        }
        CollocationPackageBean collocationPackageBean = data.get(groupPosition);
        parentViewHolder.tv_collocation_name.setText(TextUtils.isEmpty(collocationPackageBean.getName()) ? "優惠套餐" : collocationPackageBean.getName());
        parentViewHolder.tv_save_text.setText("立?。? + collocationPackageBean.getDiscountFee());
        parentViewHolder.iv_status.setImageResource(isExpanded ? R.mipmap.icon_top : R.mipmap.icon_bottom);
        parentViewHolder.v_space.setVisibility(isExpanded ? View.GONE : View.VISIBLE);
        parentViewHolder.hsv_goods_list.setVisibility(isExpanded ? View.GONE : View.VISIBLE);
        parentViewHolder.hsv_goods_list.setFocusable(false);//設置后解決套餐無法正常展開的bug
        if (!isExpanded) {
            //設置套餐折疊時顯示套餐商品的圖片
            initGoodsImage(collocationPackageBean, parentViewHolder, groupPosition);
        }
        return convertView;
    }

    @Override
    public View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ChildViewHolder childViewHolder;
        if (null == convertView) {
            convertView = inflater.inflate(R.layout.collocation_list_item_child, parent, false);
            childViewHolder = new ChildViewHolder(convertView);
            convertView.setTag(childViewHolder);
            AutoUtils.auto(convertView);
        } else {
            childViewHolder = (ChildViewHolder) convertView.getTag();
        }
        final CollocationPackageBean.CollocationSkuBean collocationSkuBean = data.get(groupPosition).getCollocationSkuDoList().get(childPosition);
        childViewHolder.sdv_goods_img.setImageURI(Uri.parse(collocationSkuBean.getImageMd5()));
        childViewHolder.tv_goods_title.setText(collocationSkuBean.getSkuTitle());
        childViewHolder.ll_root_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //進入商品詳情頁操作
            }
        });
        if (childPosition == data.get(groupPosition).getCollocationSkuDoList().size() - 1) {
            //當前套餐的最后一個商品
            childViewHolder.ll_bottom.setVisibility(View.VISIBLE);
            childViewHolder.tv_collocation_price.setText(data.get(groupPosition).getTotalPrice().toString());
            childViewHolder.tv_add_cart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //把套餐商品加入購物車操作
                }
            });
        } else {
            childViewHolder.ll_bottom.setVisibility(View.GONE);
        }
        return convertView;
    }

    class ParentViewHolder {
        private View v_space;
        private ImageView iv_status;
        private HorizontalScrollView hsv_goods_list;
        private TextView tv_collocation_name, tv_save_text;

        private ParentViewHolder (View view) {
            v_space = view.findViewById(R.id.v_space);
            iv_status = (ImageView) view.findViewById(R.id.iv_status);
            hsv_goods_list = (HorizontalScrollView) view.findViewById(R.id.hsv_goods_list);
            tv_collocation_name = (TextView) view.findViewById(R.id.tv_collocation_name);
            tv_save_text = (TextView) view.findViewById(R.id.tv_save_text);
        }
    }

    private class ChildViewHolder {
        private SimpleDraweeView sdv_goods_img;
        private LinearLayout ll_bottom, ll_root_view;
        private TextView tv_add_cart, tv_goods_title, tv_collocation_price;

        private ChildViewHolder (View view) {
            sdv_goods_img = (SimpleDraweeView) view.findViewById(R.id.sdv_goods_img);
            ll_bottom = (LinearLayout) view.findViewById(R.id.ll_bottom);
            ll_root_view = (LinearLayout) view.findViewById(R.id.ll_root_view);
            tv_add_cart = (TextView) view.findViewById(R.id.tv_add_cart);
            tv_goods_title = (TextView) view.findViewById(R.id.tv_goods_title);
            tv_collocation_price = (TextView) view.findViewById(R.id.tv_collocation_price);
        }
    }

    /**
     * 初始化并設置套餐折疊時的所有商品圖片
     * @param collocationPackageBean
     * @param parentViewHolder
     * @param groupPosition
     */
    private void initGoodsImage(CollocationPackageBean collocationPackageBean,
                                ParentViewHolder parentViewHolder, final int groupPosition) {
        View collocationView;
        SimpleDraweeView sdv_cart_image;
        RelativeLayout rl_middle;
        LinearLayout rootview = new LinearLayout(context);
        for (int i = 0, len = collocationPackageBean.getCollocationSkuDoList().size(); i < len; i++) {
            collocationView = inflater.inflate(R.layout.item_gift_img, null);
            sdv_cart_image = (SimpleDraweeView) collocationView.findViewById(R.id.sdv_cart_image);
            rl_middle = (RelativeLayout) collocationView.findViewById(R.id.rl_middle);
            sdv_cart_image.setImageURI(Uri.parse(collocationPackageBean.getCollocationSkuDoList().get(i).getImageMd5()));
            rl_middle.setVisibility(View.INVISIBLE);
            collocationView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //手動實現展開操作
                    elv_collocation.expandGroup(groupPosition);
                }
            });
            AutoUtils.auto(collocationView);
            rootview.addView(collocationView);
        }
        parentViewHolder.hsv_goods_list.removeAllViews();
        parentViewHolder.hsv_goods_list.addView(rootview);
    }
}
  • collocation_list_item_child.xml

套餐子布局

<com.zhy.autolayout.AutoLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:clickable="true"
    android:orientation="vertical">

    <com.zhy.autolayout.AutoLinearLayout
        android:id="@+id/ll_root_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/selector_me_bg_item"
        android:paddingBottom="28px"
        android:paddingLeft="24px"
        android:paddingRight="24px"
        android:paddingTop="30px">

        <com.facebook.drawee.view.SimpleDraweeView
            android:id="@+id/sdv_goods_img"
            android:layout_width="120px"
            android:layout_height="120px"
            android:background="@drawable/shape_cart_goods_border"
            android:padding="1dp"
            fresco:placeholderImage="@mipmap/icon_loading_bg" />

        <TextView
            android:id="@+id/tv_goods_title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20px"
            android:layout_weight="1"
            android:ellipsize="end"
            android:maxLines="2"
            android:textColor="#222222"
            android:textSize="30px" />

        <View
            android:layout_width="118px"
            android:layout_height="1px" />

        <ImageView
            android:layout_width="18px"
            android:layout_height="28px"
            android:src="@mipmap/icon_right" />
    </com.zhy.autolayout.AutoLinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:layout_marginLeft="24px"
        android:background="#dddddd" />

    <com.zhy.autolayout.AutoLinearLayout
        android:id="@+id/ll_bottom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <com.zhy.autolayout.AutoLinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:paddingLeft="24px"
            android:paddingRight="24px"
            android:paddingTop="20px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="套餐價格:"
                android:textColor="#888888"
                android:textSize="30px" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20px"
                android:text="¥"
                android:textColor="#ec0f38"
                android:textSize="22px" />

            <TextView
                android:id="@+id/tv_collocation_price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#ec0f38"
                android:textSize="30px" />

            <View
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_weight="1" />

            <TextView
                android:id="@+id/tv_add_cart"
                android:layout_width="180px"
                android:layout_height="50px"
                android:background="@drawable/selector_add_cart_red_btn"
                android:gravity="center"
                android:text="加入購物車"
                android:textColor="@drawable/selector_add_cart_red_tv"
                android:textSize="28px" />
        </com.zhy.autolayout.AutoLinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="20px"
            android:layout_marginTop="20px"
            android:background="#eeeff3" />
    </com.zhy.autolayout.AutoLinearLayout>
</com.zhy.autolayout.AutoLinearLayout>
  • collocation_list_item_parent.xml

套餐父布局

<com.zhy.autolayout.AutoLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    android:paddingTop="20px">

    <com.zhy.autolayout.AutoLinearLayout
        android:layout_width="match_parent"
        android:layout_height="50px"
        android:layout_marginBottom="30px"
        android:gravity="center_vertical"
        android:paddingLeft="24px"
        android:paddingRight="24px">

        <TextView
            android:id="@+id/tv_collocation_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#222222"
            android:textSize="30px" />

        <TextView
            android:id="@+id/tv_save_text"
            android:layout_width="wrap_content"
            android:layout_height="40px"
            android:layout_marginLeft="20px"
            android:background="@drawable/shape_save_money"
            android:gravity="center"
            android:paddingLeft="18px"
            android:paddingRight="18px"
            android:textColor="#ffffff"
            android:textSize="24px" />

        <View
            android:layout_width="0dp"
            android:layout_height="1px"
            android:layout_weight="1" />

        <ImageView
            android:id="@+id/iv_status"
            android:layout_width="28px"
            android:layout_height="18px"
            android:layout_gravity="right|center_vertical"
            android:src="@mipmap/icon_top" />
    </com.zhy.autolayout.AutoLinearLayout>

    <HorizontalScrollView
        android:id="@+id/hsv_goods_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="24px"
        android:scrollbars="none" />

    <View
        android:id="@+id/v_space"
        android:layout_width="match_parent"
        android:layout_height="20px"
        android:layout_marginTop="20px"
        android:background="#eeeff3"
        android:visibility="gone" />
</com.zhy.autolayout.AutoLinearLayout>
  • item_gift_img.xml

圖片item布局
SimpleDraweeViewFresco里的控件, 顯示網絡圖片

<com.zhy.autolayout.AutoLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    android:orientation="horizontal">

    <com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/sdv_cart_image"
        android:layout_width="126px"
        android:layout_height="126px"
        android:background="@drawable/shape_cart_goods_border"
        android:padding="1px"
        android:scaleType="fitXY"
        fresco:placeholderImage="@mipmap/icon_loading_bg"
        fresco:progressBarImage="@mipmap/icon_loading_bg" />

    <com.zhy.autolayout.AutoRelativeLayout
        android:id="@+id/rl_middle"
        android:layout_width="wrap_content"
        android:layout_height="126px"
        android:layout_marginLeft="13px"
        android:layout_marginRight="13px"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_gift_goods_num"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_gravity="bottom"
            android:text="x1"
            android:textColor="#ec0f38"
            android:textSize="26px" />
    </com.zhy.autolayout.AutoRelativeLayout>
</com.zhy.autolayout.AutoLinearLayout>
  • CollocationPackageBean.java

存放數據的bean

public class CollocationPackageBean {
    private BigDecimal totalPrice;
    private String name;
    private List<CollocationSkuBean> collocationSkuDoList;
    private BigDecimal discountFee;

    public static class CollocationSkuBean {
        private String skuTitle;
        private String imageMd5;

        public CollocationSkuBean(String skuTitle, String imageMd5) {
            this.skuTitle = skuTitle;
            this.imageMd5 = imageMd5;
        }
        
        set...
        get..
    }
        set...
        get...
}

幾個主要的文件就這幾個
其他哪些shape, selector文件之類的就沒有必要貼上來了


需要要看詳細的代碼看這里
github源碼地址 歡迎star、fork

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容