购物车demo(内含bug)


bean层加一个isChecked 确认是否选中

private boolean isChecked;

    public boolean isChecked() {
        return isChecked;
    }

    public void setChecked(boolean checked) {
        isChecked = checked;
    }

最里层的isCheck要返回select!=0 因为后面是根据int类型的0和1判断的 setCheckAll(1);
如果点击全选为1,所以如果点击不为0

public boolean isChecked() {
            return selected!=0;
        }

自定义加减(要public)

public void setCurrentCount(int number) {
        tv_num.setText(number+"");
    }

点击全选
是setOnCheckedChangeListener方法 , 不是setOnClickListener
点击全选后要刷新

private void setCheckAll(int i) {
    //获取分组的数量
    int groupCount = showAdapter.getGroupCount();
    for (int j = 0; j < groupCount; j++) {
        //获取到子条目
        ShowBean.DataBean dataBean = (ShowBean.DataBean) showAdapter.getGroup(j);
        List<ShowBean.DataBean.ListBean> list = dataBean.getList();
        //循环选中
        for (int k = 0; k < list.size(); k++) {
            ShowBean.DataBean.ListBean listBean = list.get(k);
            listBean.setSelected(i);
        }
    }
    showAdapter.notifyDataSetChanged();
}

布局中要加入
android:descendantFocusability=“blocksDescendants”
以防止焦点冲突

开始代码

从MainActivity开始

package com.jia.myshoppingcar;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.jia.myshoppingcar.adapt.ShowAdapter;
import com.jia.myshoppingcar.bean.ShowBean;
import com.jia.myshoppingcar.presenter.ShowPresenter;
import com.jia.myshoppingcar.view.ShowView;

import java.util.List;

public class MainActivity extends AppCompatActivity implements ShowView {

private ExpandableListView expandableListView;
private CheckBox check_all;
private TextView total_price;
private ShowAdapter showAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
    ShowPresenter showPresenter = new ShowPresenter(this);
    showPresenter.show();
    clickCheckAll();
}

private void clickCheckAll() {
    check_all.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked){
                setCheckAll(1);
            }else{
                setCheckAll(0);
            }
        }
    });
}

private void setCheckAll(int i) {
    //获取分组的数量
    int groupCount = showAdapter.getGroupCount();
    for (int j = 0; j < groupCount; j++) {
        //获取到子条目
        ShowBean.DataBean dataBean = (ShowBean.DataBean) showAdapter.getGroup(j);
        List<ShowBean.DataBean.ListBean> list = dataBean.getList();
        //循环选中
        for (int k = 0; k < list.size(); k++) {
            ShowBean.DataBean.ListBean listBean = list.get(k);
            listBean.setSelected(i);
        }
    }
    getTotal();
    showAdapter.notifyDataSetChanged();
}
//计算总价
private void getTotal() {
    //默认总价为0
    double total = 0;
    int groupCount = showAdapter.getGroupCount();
    for (int i = 0; i < groupCount; i++) {
        //获取条目数量
        ShowBean.DataBean dataBean = (ShowBean.DataBean) showAdapter.getGroup(i);
        List<ShowBean.DataBean.ListBean> list = dataBean.getList();
        for (int j = 0; j < list.size(); j++) {
            ShowBean.DataBean.ListBean listBean = list.get(j);
            //判断是否选中
            boolean checked = listBean.isChecked();
            if (checked) {
                double price = listBean.getPrice();
                //如果选中,计算总价
                total+=price*listBean.getNum();
            }
        }
        total_price.setText("合计:"+total);

    }
}

private void initView() {
    expandableListView = findViewById(R.id.expandableListView);
    check_all = findViewById(R.id.check_all);
    total_price = findViewById(R.id.total_price);
}

@Override
public void onShowViewSuccess(final List<ShowBean.DataBean> dataBeans) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            showAdapter = new ShowAdapter(MainActivity.this,dataBeans);
            expandableListView.setAdapter(showAdapter);
            //展开分组
            for (int i = 0; i < dataBeans.size(); i++) {
                expandableListView.expandGroup(i);
            }
            initPriceChanged();
        }
    });
}

private void initPriceChanged() {
    expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
        @Override
        public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
            ShowBean.DataBean dataBean = (ShowBean.DataBean) showAdapter.getGroup(groupPosition);
            dataBean.setChecked(!dataBean.isChecked());
            int c = 0;
            //不选中为0,选中为1
            if(dataBean.isChecked()){
                c = 1;
            }
            List<ShowBean.DataBean.ListBean> list = dataBean.getList();
            for (int i = 0; i < list.size(); i++) {
                ShowBean.DataBean.ListBean listBean = list.get(i);
                listBean.setSelected(c);
            }
            showAdapter.notifyDataSetChanged();
            getTotal();
            return true;
        }
    });
    expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
           ShowBean.DataBean.ListBean listBean = (ShowBean.DataBean.ListBean) showAdapter.getChild(groupPosition,childPosition);
            boolean checked = listBean.isChecked();
            if(checked){
                listBean.setSelected(0);
            }else{
                listBean.setSelected(1);
            }
            showAdapter.notifyDataSetChanged();
            getTotal();
            return true;
        }
    });
}

@Override
public void onShowViewFailure(String msg) {

}

}
封装网络工具类(注意要在Application中初始化 清单文件中添加application的name)
package com.jia.myshoppingcar.utils;

import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;

public class OkHttpUtils {

    private static OkHttpUtils okHttpUtils = new OkHttpUtils();
    private static OkHttpClient okHttpClient;

private OkHttpUtils(){}
public static OkHttpUtils init(){
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.readTimeout(3000,TimeUnit.MILLISECONDS);
    builder.writeTimeout(3000,TimeUnit.MILLISECONDS);
    builder.connectTimeout(3000,TimeUnit.MILLISECONDS);
    okHttpClient = builder.build();
    return okHttpUtils;
}
public static Request createRequest(String url,String method){
    Request.Builder builder = new Request.Builder().url(url);
    Request request = builder.build();
    return request;
}
public static void enqueueGet(String url, Callback callback){
    Request request = createRequest(url, "GET");
    Call call = okHttpClient.newCall(request);
    call.enqueue(callback);
}

}
Model
package com.jia.myshoppingcar.model;

import com.google.gson.Gson;
import com.jia.myshoppingcar.bean.ShowBean;
import com.jia.myshoppingcar.callback.ShowCallBack;
import com.jia.myshoppingcar.utils.OkHttpUtils;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ShowModel {
    public void show(final ShowCallBack showCallBack){
        String url = "http://120.27.23.105/product/getCarts?source=android&uid=99";
        OkHttpUtils.enqueueGet(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String s = response.body().string();
            Gson gson = new Gson();
            ShowBean showBean = gson.fromJson(s, ShowBean.class);
            List<ShowBean.DataBean> data = showBean.getData();
            if (showBean.getCode().equals("0")) {
                showCallBack.onShowCallBackSuccess(data);
            }else {
                showCallBack.onShowCallBackFailure("展示失败");
            }
        }
    });
}

}

View
package com.jia.myshoppingcar.view;

import com.jia.myshoppingcar.bean.ShowBean;

import java.util.List;

public interface ShowView {
    void onShowViewSuccess(List<ShowBean.DataBean> dataBeans);
    void onShowViewFailure(String msg);
}

Presenter
package com.jia.myshoppingcar.presenter;

import com.jia.myshoppingcar.callback.ShowCallBack;
import com.jia.myshoppingcar.model.ShowModel;
import com.jia.myshoppingcar.view.ShowView;

import java.util.List;

public class ShowPresenter {
    private ShowView showView;
    private final ShowModel showModel;

public ShowPresenter(ShowView showView) {
    this.showView = showView;
    showModel = new ShowModel();
}
public void show(){
    showModel.show(new ShowCallBack() {
        @Override
        public void onShowCallBackSuccess(List list) {
            showView.onShowViewSuccess(list);
        }

        @Override
        public void onShowCallBackFailure(String msg) {
            showView.onShowViewFailure(msg);
        }
    });
}

}

CallBack
package com.jia.myshoppingcar.callback;

import com.jia.myshoppingcar.bean.ShowBean;

import java.util.List;

public interface ShowCallBack<T> {
    void onShowCallBackSuccess(List<ShowBean.DataBean> dataBeans);
    void onShowCallBackFailure(String msg);
}

自定义加减器
package com.jia.myshoppingcar.custom;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jia.myshoppingcar.R;

public class AddNum extends LinearLayout {

private TextView tv_add;
private TextView tv_num;
private TextView tv_reduce;

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

public AddNum(Context context, AttributeSet attrs) {
    this(context, attrs,-1);
}

public AddNum(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initView(context);
    initListener();
}

private void initListener() {
    tv_add.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            String num = tv_num.getText().toString();
            int parseInt = Integer.parseInt(num);
            parseInt++;
            setCurrentCount(parseInt);
        }
    });
    tv_reduce.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            String num = tv_num.getText().toString();
            int parseInt = Integer.parseInt(num);
            if(parseInt>1){
                parseInt--;
                setCurrentCount(parseInt);
            }else{
                Toast.makeText(getContext(),"不能再减了",Toast.LENGTH_SHORT).show();
            }
        }
    });
}

public void setCurrentCount(int number) {
    tv_num.setText(number+"");

}


private void initView(Context context) {
    View view = View.inflate(context, R.layout.addnum, this);
    tv_add = view.findViewById(R.id.tv_add);
    tv_num = view.findViewById(R.id.tv_num);
    tv_reduce = view.findViewById(R.id.tv_reduce);
    tv_num.setText("1");
}

}
适配器
package com.jia.myshoppingcar.adapt;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.jia.myshoppingcar.R;
import com.jia.myshoppingcar.bean.ShowBean;
import com.jia.myshoppingcar.custom.AddNum;
import com.squareup.picasso.Picasso;

import java.util.List;

public class ShowAdapter extends BaseExpandableListAdapter {
    private Context context;
    private List<ShowBean.DataBean> dataBeans;

public ShowAdapter(Context context, List<ShowBean.DataBean> dataBeans) {
    this.context = context;
    this.dataBeans = dataBeans;
}

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

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

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

@Override
public Object getChild(int groupPosition, int childPosition) {
    return dataBeans.get(groupPosition).getList().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 View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
    GroupViewHolder groupViewHolder = null;
    if(convertView == null){
        convertView = View.inflate(context, R.layout.group_view,null);
        groupViewHolder = new GroupViewHolder();
        groupViewHolder.checked_title = convertView.findViewById(R.id.checked_title);
        groupViewHolder.group_title = convertView.findViewById(R.id.group_title);
        convertView.setTag(groupViewHolder);
    }else{
        groupViewHolder = (GroupViewHolder) convertView.getTag();
    }
    groupViewHolder.checked_title.setChecked(dataBeans.get(groupPosition).isChecked());
    groupViewHolder.group_title.setText(dataBeans.get(groupPosition).getSellerName());
    return convertView;
}

@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
    ChildViewHolder childViewHolder = null;
    if(convertView == null){
        convertView = View.inflate(context,R.layout.child_view,null);
        childViewHolder = new ChildViewHolder();
        childViewHolder.check_item = convertView.findViewById(R.id.check_item);
        childViewHolder.child_image = convertView.findViewById(R.id.child_image);
        childViewHolder.child_title = convertView.findViewById(R.id.child_title);
        childViewHolder.child_price = convertView.findViewById(R.id.child_price);
        childViewHolder.addNum = convertView.findViewById(R.id.addNum);
        convertView.setTag(childViewHolder);
    }else {
        childViewHolder = (ChildViewHolder) convertView.getTag();
    }
    ShowBean.DataBean.ListBean listBean = dataBeans.get(groupPosition).getList().get(childPosition);
    childViewHolder.check_item.setChecked(listBean.isChecked());
    Picasso.with(context).load(listBean.getImages().split("\\|")[0]).into(childViewHolder.child_image);
    childViewHolder.child_title.setText(listBean.getTitle());
    childViewHolder.child_price.setText(listBean.getPrice()+"");
    childViewHolder.addNum.setCurrentCount(listBean.getNum());
    return convertView;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}
class GroupViewHolder{
    CheckBox checked_title;
    TextView group_title;
}
class ChildViewHolder{
    CheckBox check_item;
    ImageView child_image;
    TextView child_title;
    TextView child_price;
    AddNum addNum;
}

}
Bean类里有一些要注意的
package com.jia.myshoppingcar.bean;

import java.util.List;

public class ShowBean {

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;
}

@Override
public String toString() {
    return "ShowBean{" +
            "msg='" + msg + '\'' +
            ", code='" + code + '\'' +
            ", data=" + data +
            '}';
}

public static class DataBean {

    private String sellerName;
    private String sellerid;
    private List<ListBean> list;
    private boolean isChecked;

    public boolean isChecked() {
        return isChecked;
    }

    public void setChecked(boolean checked) {
        isChecked = 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;
    }

    @Override
    public String toString() {
        return "DataBean{" +
                "sellerName='" + sellerName + '\'' +
                ", sellerid='" + sellerid + '\'' +
                ", list=" + list +
                '}';
    }

    public static class ListBean {

        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;
        private boolean isChecked;

        public boolean isChecked() {
            return selected!=0;
        }

        public void setChecked(boolean checked) {
            isChecked = 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;
        }

        @Override
        public String toString() {
            return "ListBean{" +
                    "bargainPrice=" + bargainPrice +
                    ", createtime='" + createtime + '\'' +
                    ", detailUrl='" + detailUrl + '\'' +
                    ", images='" + images + '\'' +
                    ", num=" + num +
                    ", pid=" + pid +
                    ", price=" + price +
                    ", pscid=" + pscid +
                    ", selected=" + selected +
                    ", sellerid=" + sellerid +
                    ", subhead='" + subhead + '\'' +
                    ", title='" + title + '\'' +
                    '}';
        }
    }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值