MVP+二级购物车+自定义View加减号

本文介绍了一种使用MVP架构在Android中实现二级购物车加减功能的方法,包括所需的依赖、布局文件activity_cart.xml和adddelete.xml的设置,以及自定义View的实现,涉及到ICartModel、ICartView接口和Urls、MessagEvent的相关操作。

效果图:


需要的依赖:

//retrofit2的依赖
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
//rxJava2的依赖
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
// Because RxAndroid releases are few and far between, it is recommended you also
// explicitly depend on RxJava's latest version for bug fixes and new features.
compile 'io.reactivex.rxjava2:rxjava:2.1.7'
//拦截器的依赖
compile 'com.squareup.okhttp3:logging-interceptor:3.9.1'
//recyclerview的依赖
implementation 'com.android.support:recyclerview-v7:26.1.0'
//eventbus的依赖
compile 'org.greenrobot:eventbus:3.0.0'
//Fresco的依赖
compile 'com.facebook.fresco:fresco:1.5.0'
---------------------------------------XML布局----------------------------------

activity_cart.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.erjicarts.view.activity.CartActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_centerVertical="true"
            android:background="@drawable/leftjiantou" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="购物车"
            android:textColor="#000"
            android:textSize="25sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="20dp"
            android:text="编辑" />
    </RelativeLayout>


    <ExpandableListView
        android:id="@+id/elv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_alignParentBottom="true"
        android:background="@android:color/white"
        android:gravity="center_vertical">
<CheckBox
    android:id="@+id/cb_All"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_marginLeft="10dp"
    android:checked="true"
    android:focusable="false" />
<TextView android:id="@+id/tv_quxuan" android:layout_width="wrap_content" android:layout_height="50dp" android:layout_centerVertical="true" android:layout_marginLeft="10dp" android:layout_toRightOf="@+id/cb_All" android:gravity="center_vertical" android:text="全选" android:textSize="20sp" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/tv_quxuan" android:orientation="vertical"> <TextView android:id="@+id/tv_price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:text="合计 :¥550.90" android:textSize="25dp" /> <TextView android:id="@+id/tv_carts_price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:text="总额:582.70 立减:¥31.80" /> </LinearLayout> <TextView android:id="@+id/tv_num" android:layout_width="120dp" android:layout_height="match_parent" android:layout_alignParentRight="true" android:background="@android:color/holo_red_dark" android:gravity="center" android:padding="10dp" android:text="去结算(0)" android:textColor="@android:color/white" /> </RelativeLayout></LinearLayout>
cart_child_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/del"
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:orientation="horizontal">

    <CheckBox
        android:id="@+id/cb_child"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="45dp"
        android:focusable="false" />


    <com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/child_sdv"
        android:layout_width="100dp"
        android:layout_height="match_parent"
        android:layout_margin="8dp"
        app:placeholderImage="@mipmap/ic_launcher_round" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:orientation="vertical"
        android:padding="10dp">

        <TextView
            android:id="@+id/child_tit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="123"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/child_info"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:text="颜色:黑;尺寸:23L" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/child_price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:textColor="@color/colorAccent" />

            <com.example.erjicarts.view.AddDeleteView
                android:id="@+id/adv_main"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_weight="1"
                app:left_text="-"
                app:middle_text="1"
                app:right_text="+" />
        </RelativeLayout>

    </LinearLayout>
</LinearLayout>
cart_group_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:orientation="horizontal">

    <CheckBox
        android:id="@+id/cb_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="30dp"
        android:focusable="false" />

    <TextView
        android:id="@+id/gou_dian"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="30dp"
        android:text="标记" />
</LinearLayout>
//自定义View的布局

adddelete.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_delete"
        android:layout_width="31dp"
        android:layout_height="31dp"
        android:background="#999999"
        android:gravity="center"
        android:text="-"
        android:textSize="20sp" />

    <EditText
        android:id="@+id/ed_num"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@null"
        android:gravity="center" />

    <TextView
        android:id="@+id/tv_add"
        android:layout_width="31dp"
        android:layout_height="31dp"
        android:background="#999999"
        android:gravity="center"
        android:text="+"
        android:textSize="20sp" />
</LinearLayout>
//自定义View

先在values下创建attrs.xml文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="AddDeleteViewStyle">
        <attr name="left_text" format="string" />
        <attr name="right_text" format="string" />
        <attr name="middle_text" format="string" />
    </declare-styleable>
</resources>
然后创建AddDeleteView,继承LinearLayout

public class AddDeleteView extends LinearLayout {

    private OnAddDelClickListener listener;
    private EditText etNumber;

    //对外提供一个点击的回调接口
    public interface OnAddDelClickListener {
        void onAddClick(View v);

        void onDelClick(View v);
    }

    public void setOnAddDelClickListener(OnAddDelClickListener listener) {
        if (listener != null) {
            this.listener = listener;
        }
    }

    public AddDeleteView(Context context) {
        this(context, null);
    }

    public AddDeleteView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AddDeleteView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        initView(context, attrs, defStyleAttr);
    }

    private void initView(Context context, AttributeSet attrs, int defStyleAttr) {
        View.inflate(context, R.layout.adddelete, this);
        TextView txtDelete = (TextView) findViewById(R.id.tv_delete);
        TextView txtAdd = (TextView) findViewById(R.id.tv_add);
        etNumber = (EditText) findViewById(R.id.ed_num);


        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AddDeleteViewStyle);

        String leftText = typedArray.getString(R.styleable.AddDeleteViewStyle_left_text);
        String rightText = typedArray.getString(R.styleable.AddDeleteViewStyle_right_text);
        String middleText = typedArray.getString(R.styleable.AddDeleteViewStyle_middle_text);

        txtDelete.setText(leftText);
        txtAdd.setText(rightText);
        etNumber.setText(middleText);

        //回收
        typedArray.recycle();


        txtDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onDelClick(view);
            }
        });

        txtAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onAddClick(view);
            }
        });

    }

    //对外提供一个修改数字的方法
    public void setNumber(int number) {
        if (number > 0) {
            etNumber.setText(number + "");
        }
    }

    //对外提供一个获取当前数字的方法
    public int getNumber() {
        String string = etNumber.getText().toString();
        int i = Integer.parseInt(string);
        return i;
    }
    
}
Model层

ICartModel

public interface ICartModel {
    public void getCart(String uid, OnNetListener<CartBean> onNetListener);
}
CartModel

public class CartModel implements ICartModel {
    @Override
    public void getCart(String uid, final OnNetListener<CartBean> onNetListener) {
        ServiceApi serviceApi = RetrofitHelper.getAPI();
        serviceApi.getCarts(uid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<CartBean>() {
                    @Override
                    public void accept(CartBean cartBean) throws Exception {
                        onNetListener.onSuccess(cartBean);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        onNetListener.onFailure((Exception) throwable);
                    }
                });
    }
}
Presenter层

public class CartPresenter {

    private final ICartModel iCartModel;
    private ICartView iCartView;

    public CartPresenter(ICartView iCartView) {
        this.iCartView = iCartView;
        iCartModel = new CartModel();
    }

    public void getCarts() {
        iCartModel.getCart("71", new OnNetListener<CartBean>() {
            @Override
            public void onSuccess(CartBean cartBean) {
                iCartView.getCarts(cartBean);
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }

    @Override
    public void detachView() {
        //防止内存泄露
        if (iCartView != null) {
            iCartView = null;
            System.gc();
        }
    }
}
View层

ICartView

public interface ICartView {
    public void getCarts(CartBean cartBean);
}
CartActivity

public class CartActivity extends AppCompatActivity implements ICartView {

    private ExpandableListView mElv;
    private CheckBox mCbAll;
    /**
     * 全选
     */
    private TextView mTvQuxuan;
    /**
     * 合计 :¥550.90
     */
    private TextView mTvPrice;
    /**
     * 总额:582.70  立减:¥31.80
     */
    private TextView mTvCartsPrice;
    /**
     * 去结算(0)
     */
    private TextView mTvNum;
    private List<List<CartBean.DataBean.ListBean>> lists;
    private MyElvAdapter myElvAdapter;
    private CartPresenter cartPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);
        initView();
        EventBus.getDefault().register(this);

        cartPresenter = new CartPresenter(this);
        cartPresenter.getCarts();
    }

   
@Override
public void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);
    
    if (cartPresenter != null) {
        cartPresenter.detachView();
        cartPresenter = null;
        System.gc();
    }
}
    private void initView() {
        mElv = (ExpandableListView) findViewById(R.id.elv);
        mCbAll = (CheckBox) findViewById(R.id.cb_All);
        mTvQuxuan = (TextView) findViewById(R.id.tv_quxuan);
        mTvPrice = (TextView) findViewById(R.id.tv_price);
        mTvCartsPrice = (TextView) findViewById(R.id.tv_carts_price);
        mTvNum = (TextView) findViewById(R.id.tv_num);
        //全选
        mCbAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myElvAdapter.changeAllListCbState(mCbAll.isChecked());
            }
        });
    }

    @Override
    public void getCarts(CartBean cartBean) {
float price = 0;
int num = 0;

List<CartBean.DataBean> dataBeans = cartBean.getData();
lists = new ArrayList<>();
for (int i = 0; i < dataBeans.size(); i++) {
    List<CartBean.DataBean.ListBean> list = dataBeans.get(i).getList();
    lists.add(list);
}
//设置适配器
myElvAdapter = new MyElvAdapter(this, dataBeans, lists);
mElv.setAdapter(myElvAdapter);
for (int i = 0; i < dataBeans.size(); i++) {
    //默认二级列表展开
    mElv.expandGroup(i);
}
//取消小箭头
mElv.setGroupIndicator(null);

//默认全选
for (int i = 0; i < lists.size(); i++) {
    for (int j = 0; j < lists.get(i).size(); j++) {
        CartBean.DataBean.ListBean listBean = lists.get(i).get(j);
        price += listBean.getNum() * listBean.getPrice();
        num += listBean.getNum();
    }
}
mTvNum.setText(num);
mTvPrice.setText(price + "");
} @Subscribe public void onMessageEvent(MessageEvent event) { mCbAll.setChecked(event.isChecked()); } @Subscribe public void onMessageEvent(PriceAndCountEvent event) { mTvPrice.setText("合计:¥" + event.getPrice() * event.getCount()); mTvCartsPrice.setText("总额:¥" + event.getPrice() * event.getCount()); mTvNum.setText("去结算(" + event.getCount() + ")"); }}
//网络请求工具类

Urls

public class Urls {
    public static final String BASE_URL = "https://www.zhaoapi.cn/";
    //商品详情
    public static final String PRODUCTDETAIL = "product/getProductDetail";
    //添加购物车
    public static final String ADDCART = "product/addCart";
    //查询购物车
    public static final String GETCARTS = "product/getCarts";

}
ServiceApi

public interface ServiceApi {
    //商品列表
    @GET(Urls.PRODUCTDETAIL)
    Observable<ProductDetailBean> getProductDetail(@Query("pid") String pid);

    //添加购物车
    @GET(Urls.ADDCART)
    Observable<AddCartBean> getAddCart(@Query("uid") String uid, @Query("pid") String pid);

    //查询购物车
    @GET(Urls.GETCARTS)
    Observable<CartBean> getCarts(@Query("uid") String uid);

}
RetrofitHelper

public class RetrofitHelper {
    private static Retrofit retrofit;

    private static ServiceApi serviceApi;

    /**
     * 初始化Retrofit 单例模式
     */
    private static Retrofit getRetrofit() {
        //线程安全
        if (retrofit == null) {
            synchronized (RetrofitHelper.class) {
                if (retrofit == null) {
                    //设置拦截器
                    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
                    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
                    OkHttpClient client = new OkHttpClient.Builder()
                            .addInterceptor(new MyInterceptor())
                            .connectTimeout(5, TimeUnit.SECONDS)//设置连接超时
                            .addInterceptor(logging)//添加拦截器
                            //.addNetworkInterceptor() //网路拦截器
                            .build();


                    retrofit = new Retrofit.Builder()
                            .baseUrl(Urls.BASE_URL)
                            .client(client)
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .build();
                }
            }
        }

        return retrofit;
    }


    public static ServiceApi getAPI() {
        if (serviceApi == null) {
            synchronized (RetrofitHelper.class) {
                if (serviceApi == null) {
                    serviceApi = getRetrofit().create(ServiceApi.class);
                }
            }
        }
        return serviceApi;
    }

    /**
     * 添加公共参数拦截器
     */
    static class MyInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            HttpUrl httpUrl = request
                    .url()
                    .newBuilder()
                    .addQueryParameter("source", "android")
                    .build();
            Request requestNew = request
                    .newBuilder()
                    .url(httpUrl)
                    .build();
            return chain.proceed(requestNew);
        }
    }
}
OnNetListener

public interface OnNetListener<T> {
    public void onSuccess(T t);

    public void onFailure(Exception e);
}
适配器

public class MyElvAdapter extends BaseExpandableListAdapter {
    private Context context;
    private List<CartBean.DataBean> groupList;
    private List<List<CartBean.DataBean.ListBean>> childList;
    private LayoutInflater inflater;

    public MyElvAdapter(Context context, List<CartBean.DataBean> groupList, List<List<CartBean.DataBean.ListBean>> childList) {
        this.context = context;
        this.groupList = groupList;
        this.childList = childList;
        inflater = LayoutInflater.from(context);
    }

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

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

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

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return childList.get(groupPosition).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 false;
    }

    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        View view;
        final GroupViewHolder holder;
        if (convertView == null) {
            holder = new GroupViewHolder();
            view = inflater.inflate(R.layout.cart_group_item, null);
            holder.cb_group = view.findViewById(R.id.cb_group);
            holder.tv_dian = view.findViewById(R.id.gou_dian);
            view.setTag(holder);
        } else {
            view = convertView;
            holder = (GroupViewHolder) view.getTag();
        }
        final CartBean.DataBean dataBean = groupList.get(groupPosition);
        holder.cb_group.setChecked(dataBean.isChecked());
        holder.tv_dian.setText(dataBean.getSellerName());
        //一级列表的Checkbox
        holder.cb_group.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataBean.setChecked(holder.cb_group.isChecked());
                //当一级选中时,改变二级列表CheckBox状态
                changeChildCbState(groupPosition, holder.cb_group.isChecked());
                //将对应的数量和价格传到PriceAndCountEvent
                EventBus.getDefault().post(computer());
                //当一级的全部选中是,改变全选CheckBox状态
                changeAllCbState(isAllGroupCbSelected());
                //刷新列表
                notifyDataSetChanged();
            }
        });
        return view;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        View view;
        final ChildViewHolder holder;
        if (convertView == null) {
            holder = new ChildViewHolder();
            view = inflater.inflate(R.layout.cart_child_item, null);
            holder.cb_child = view.findViewById(R.id.cb_child);
            holder.del = view.findViewById(R.id.del);
            holder.sdv = view.findViewById(R.id.child_sdv);
            holder.adv_main = view.findViewById(R.id.adv_main);
            holder.tv_info = view.findViewById(R.id.child_info);
            holder.tv_price = view.findViewById(R.id.child_price);
            holder.tv_tit = view.findViewById(R.id.child_tit);
            view.setTag(holder);
        } else {
            view = convertView;
            holder = (ChildViewHolder) view.getTag();
        }
        final CartBean.DataBean.ListBean listBean = childList.get(groupPosition).get(childPosition);
        holder.cb_child.setChecked(listBean.isChecked());
        String[] strings = listBean.getImages().split("\\!");
        holder.sdv.setImageURI(strings[0]);
        holder.tv_tit.setText(listBean.getSubhead());
        holder.tv_info.setText(listBean.getTitle());
        holder.tv_price.setText("" + listBean.getBargainPrice());
        //给二级CheckBox设置点击事件
        holder.cb_child.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置该条目对象里的checked属性值
                listBean.setChecked(holder.cb_child.isChecked());
                PriceAndCountEvent priceAndCountEvent = computer();
                EventBus.getDefault().post(priceAndCountEvent);

                if (holder.cb_child.isChecked()) {
                    //当前checkbox是选中状态
                    if (isAllChildCbSelected(groupPosition)) {
                        changeGroupCbState(groupPosition, true);
                        changeAllCbState(isAllGroupCbSelected());
                    }
                } else {
                    changeGroupCbState(groupPosition, false);
                    changeAllCbState(isAllGroupCbSelected());
                }
                notifyDataSetChanged();
            }
        });
        //自定义View加减号
        holder.adv_main.setOnAddDelClickListener(new AddDeleteView.OnAddDelClickListener() {
            @Override
            public void onAddClick(View v) {
                //加号
                int num = listBean.getNum();
                holder.adv_main.setNumber(++num);
                listBean.setNum(num);
                if (holder.cb_child.isChecked()) {
                    PriceAndCountEvent priceAndCountEvent = computer();
                    EventBus.getDefault().post(computer());
                }
            }

            @Override
            public void onDelClick(View v) {
                //减号
                int num = listBean.getNum();
                if (num == 1) {
                    return;
                }
                holder.adv_main.setNumber(--num);
                listBean.setNum(num);
                if (holder.cb_child.isChecked()) {
                    PriceAndCountEvent priceAndCountEvent = computer();
                    EventBus.getDefault().post(computer());
                }
            }
        });

        holder.del.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setIcon(R.mipmap.ic_launcher_round)
                        .setTitle("删除商品")
                        .setMessage("确定删除商品吗?");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        List<CartBean.DataBean.ListBean> datasBeen = childList.get(groupPosition);
                        CartBean.DataBean.ListBean remove = datasBeen.remove(childPosition);
                        if (datasBeen.size() == 0) {
                            childList.remove(groupPosition);
                            groupList.remove(groupPosition);
                        }
                        EventBus.getDefault().post(computer());
                        notifyDataSetChanged();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(context, "您取消了删除" + which, Toast.LENGTH_SHORT).show();
                    }
                });
                builder.show();
                return true;
            }
        });
        return view;
    }

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

    class GroupViewHolder {
        CheckBox cb_group;
        TextView tv_dian;
    }

    class ChildViewHolder {
        LinearLayout del;
        CheckBox cb_child;
        SimpleDraweeView sdv;
        TextView tv_tit;
        TextView tv_info;
        TextView tv_price;
        AddDeleteView adv_main;
    }

    /**
     * 改变全选CheckBox状态
     *
     * @param flag
     */
    private void changeAllCbState(boolean flag) {
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setChecked(flag);
        EventBus.getDefault().post(messageEvent);
    }

    /**
     * 改变二级列表CheckBox状态
     *
     * @param groupPosition
     * @param flag
     */
    private void changeChildCbState(int groupPosition, boolean flag) {
        List<CartBean.DataBean.ListBean> listBeans = childList.get(groupPosition);
        for (int i = 0; i < listBeans.size(); i++) {
            CartBean.DataBean.ListBean listBean = listBeans.get(i);
            listBean.setChecked(flag);
        }
    }

    /**
     * 改变一级列表CheckBox状态
     *
     * @param groupPosition
     * @param flag
     */
    private void changeGroupCbState(int groupPosition, boolean flag) {
        CartBean.DataBean dataBean = groupList.get(groupPosition);
        dataBean.setChecked(flag);
    }

    /**
     * 判断一级列表是否全部选中
     *
     * @return
     */
    public boolean isAllGroupCbSelected() {
        for (int i = 0; i < groupList.size(); i++) {
            CartBean.DataBean dataBean = groupList.get(i);
            if (!dataBean.isChecked()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断二级列表是否全部选中
     *
     * @param groupPosition
     * @return
     */
    public boolean isAllChildCbSelected(int groupPosition) {
        List<CartBean.DataBean.ListBean> listBeans = childList.get(groupPosition);
        for (int i = 0; i < listBeans.size(); i++) {
            CartBean.DataBean.ListBean listBean = listBeans.get(i);
            if (!listBean.isChecked()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 设置全选、反选
     *
     * @param flag
     */
    public void changeAllListCbState(boolean flag) {
        for (int i = 0; i < groupList.size(); i++) {
            //改变一级列表CheckBox状态
            changeGroupCbState(i, flag);
            //改变二级列表CheckBox状态
            changeChildCbState(i, flag);
        }
        //将数量和价格传值
        EventBus.getDefault().post(computer());
        //刷新列表
        notifyDataSetChanged();
    }

    /**
     * 计算列表中选中的钱和数量
     *
     * @return
     */
    private PriceAndCountEvent computer() {
        int count = 0;
        int price = 0;
        for (int i = 0; i < childList.size(); i++) {
            List<CartBean.DataBean.ListBean> listBeans = childList.get(i);
            for (int j = 0; j < listBeans.size(); j++) {
                CartBean.DataBean.ListBean listBean = listBeans.get(j);
                if (listBean.isChecked()) {
                    count += listBean.getNum();
                    price += listBean.getNum() * listBean.getPrice();
                }
            }
        }
        PriceAndCountEvent priceAndCountEvent = new PriceAndCountEvent();
        priceAndCountEvent.setCount(count);
        priceAndCountEvent.setPrice(price);
        return priceAndCountEvent;
    }
}

MessagEvent

public class MessageEvent {
    private boolean checked;

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }
}
PriceAndCountEvent

public class PriceAndCountEvent {
    private int price;
    private int count;

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}
MyApp

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        //配置磁盘缓存
        DiskCacheConfig diskSmallCacheConfig = DiskCacheConfig.newBuilder(this)
                .setBaseDirectoryPath(this.getCacheDir())//缓存图片基路径
                .setBaseDirectoryName(getString(R.string.app_name))//文件夹名
                .build();
        ImagePipelineConfig imagePipelineConfig = ImagePipelineConfig.newBuilder(this)
                .setBitmapsConfig(Bitmap.Config.RGB_565)
                .setSmallImageDiskCacheConfig(diskSmallCacheConfig)
                .build();
        /**
         * 初始化Fresco
         */
        Fresco.initialize(this, imagePipelineConfig);
    }
}

CartBean

public class CartBean {

    private String msg;
    private String code;
    private List<DataBean> data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {

        private boolean checked = true;
        private String sellerName;
        private String sellerid;
        private List<ListBean> list;

        public boolean isChecked() {
            return checked;
        }

        public void setChecked(boolean checked) {
            this.checked = checked;
        }

        public String getSellerName() {
            return sellerName;
        }

        public void setSellerName(String sellerName) {
            this.sellerName = sellerName;
        }

        public String getSellerid() {
            return sellerid;
        }

        public void setSellerid(String sellerid) {
            this.sellerid = sellerid;
        }

        public List<ListBean> getList() {
            return list;
        }

        public void setList(List<ListBean> list) {
            this.list = list;
        }

        public static class ListBean {
           
            private boolean checked = true;
            private double bargainPrice;
            private String createtime;
            private String detailUrl;
            private String images;
            private int num;
            private int pid;
            private double price;
            private int pscid;
            private int selected;
            private int sellerid;
            private String subhead;
            private String title;

            public boolean isChecked() {
                return checked;
            }

            public void setChecked(boolean checked) {
                this.checked = checked;
            }

            public double getBargainPrice() {
                return bargainPrice;
            }

            public void setBargainPrice(double bargainPrice) {
                this.bargainPrice = bargainPrice;
            }

            public String getCreatetime() {
                return createtime;
            }

            public void setCreatetime(String createtime) {
                this.createtime = createtime;
            }

            public String getDetailUrl() {
                return detailUrl;
            }

            public void setDetailUrl(String detailUrl) {
                this.detailUrl = detailUrl;
            }

            public String getImages() {
                return images;
            }

            public void setImages(String images) {
                this.images = images;
            }

            public int getNum() {
                return num;
            }

            public void setNum(int num) {
                this.num = num;
            }

            public int getPid() {
                return pid;
            }

            public void setPid(int pid) {
                this.pid = pid;
            }

            public double getPrice() {
                return price;
            }

            public void setPrice(double price) {
                this.price = price;
            }

            public int getPscid() {
                return pscid;
            }

            public void setPscid(int pscid) {
                this.pscid = pscid;
            }

            public int getSelected() {
                return selected;
            }

            public void setSelected(int selected) {
                this.selected = selected;
            }

            public int getSellerid() {
                return sellerid;
            }

            public void setSellerid(int sellerid) {
                this.sellerid = sellerid;
            }

            public String getSubhead() {
                return subhead;
            }

            public void setSubhead(String subhead) {
                this.subhead = subhead;
            }

            public String getTitle() {
                return title;
            }

            public void setTitle(String title) {
                this.title = title;
            }
        }
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值