简单的准备工作
我这里按钮做了两个shape,无需多言,
布局文件
main.xml
car_add_sub_layout.xml
cart2_group_item.xml
cart_item.xml
这里最后一个有自定义类(附上) 主要实现了自定义算法数量的加减运算
public class AddSubLayout extends LinearLayout implements View.OnClickListener {
private TextView mAddBtn,mSubBtn;
private TextView mNumText;
private AddSubListener addSubListener;
public AddSubLayout(Context context) {
super(context);
initView();
}
public AddSubLayout(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public AddSubLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public AddSubLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initView();
}
private void initView(){
//加载layout布局,第三个参数ViewGroup一定写成this
View view = View.inflate(getContext(),R.layout.car_add_sub_layout,this);
mAddBtn = view.findViewById(R.id.btn_add);
mSubBtn = view.findViewById(R.id.btn_sub);
mNumText = view.findViewById(R.id.text_number);
mAddBtn.setOnClickListener(this);
mSubBtn.setOnClickListener(this);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
int width = r-l;//getWidth();
int height = b-t;//getHeight();
}
@Override
public void onClick(View v) {
int number = Integer.parseInt(mNumText.getText().toString());
switch (v.getId()){
case R.id.btn_add:
number++;
mNumText.setText(number+"");
break;
case R.id.btn_sub:
if (number==0){
Toast.makeText(getContext(),"数量不能小于0",Toast.LENGTH_LONG).show();
return;
}
number--;
mNumText.setText(number+"");
break;
}
if (addSubListener!=null){
addSubListener.addSub(number);
}
}
public void setCount(int count) {
mNumText.setText(count+"");
}
public void setAddSubListener(AddSubListener addSubListener) {
this.addSubListener = addSubListener;
}
public interface AddSubListener{
void addSub(int count);
}
}
以上是布局
下面:主要代码实现(当然你可以采用本地数据,这里我使用接口里的数据采用mvp模式获取数据)
先复一遍mvp模式(如果是自己写的bean类即可以跳过)
//接口
public interface ShangPinInter {
void success(T data);
void fail(Result result);
}
//presenter
public class ShangpinPresenter {
public ShangPinInter shangPinInter ;
public ShangpinPresenter(ShangPinInter shangPinInter) {
this.shangPinInter = shangPinInter;
}
@SuppressLint("HandlerLeak")
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Result result = (Result) msg.obj;
int code = result.getCode();
if (code == 0){
shangPinInter.success(result.getData());
}else{
shangPinInter.fail(result);
}
}
};
public void shangpinShow() {
new Thread(new Runnable() {
@Override
public void run() {
Result result = Mmodel.shangpinShow();
Message message = new Message();
message.obj = result;
handler.sendMessage(message);
}
}).start();
}
}
//model
Gson gson = new Gson();
Type type = new TypeToken>>() {
}.getType();
Result result = gson.fromJson(s4, type);
return result;
//Activity
public class Car extends Fragment implements ShangPinInter> ,CarAdapter2.TotalPriceListener{
}
以上mvp
下面是最重要的适配器以及Activity中回调适配器中的方法(接口回调):
public class Car extends Fragment implements ShangPinInter> ,CarAdapter2.TotalPriceListener{
ShangpinPresenter shangpinPresenter = new ShangpinPresenter(this);
private CarAdapter2 carAdapter2;
private ExpandableListView mGoodsList;
private CheckBox mCheckAll;
private TextView mSumPrice;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.car,container,false);
/**
*全选功能,适配器中的全选方法
*/
mCheckAll = (CheckBox) view.findViewById(R.id.check_all);
mCheckAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
carAdapter2.checkAll(isChecked);
}
});
/**
* 页面价格的回显组件
*/
mSumPrice = (TextView) view.findViewById(R.id.goods_sum_price);
/**
* 购物车的适配器
*/
mGoodsList = (ExpandableListView) view.findViewById(R.id.list_cart);
carAdapter2 = new CarAdapter2(this);
mGoodsList.setAdapter(carAdapter2);
//设置价格总调
carAdapter2.setTotalPriceListener(this);
//去掉二级列表的默认箭头
mGoodsList.setGroupIndicator(null);
//让其group不能被点击
mGoodsList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
return true;
}
});
//mvp请求数据
shangpinPresenter.shangpinShow();
return view;
}
//mvp模式成功的反应结果
@Override
public void success(List data) {
//适配器的添加对象的方法
carAdapter2.addAll(data);
//遍历所有group,将所有项设置成默认展开
int groupCount = data.size();
for (int i = 0; i < groupCount; i++) {
mGoodsList.expandGroup(i);
}
carAdapter2.notifyDataSetChanged();
}
//mvp模式失败的反应结果
@Override
public void fail(Result result) {
}
//适配器中的计算总价(接口回调实现的)...
@Override
public void totalPrice(double totalPrice) {
mSumPrice.setText(String.valueOf(totalPrice));
}
}
适配器
public class CarAdapter2 extends BaseExpandableListAdapter {
//构造的商品信息表店家中的子类商品
private List mList = new ArrayList();
//接口回调价格
private TotalPriceListener totalPriceListener;
public CarAdapter2(Car car) {
}
public void setTotalPriceListener(TotalPriceListener totalPriceListener) {
this.totalPriceListener = totalPriceListener;
}
@Override
public int getGroupCount() {
return mList.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return mList.get(groupPosition).getList().size();
}
@Override
public Object getGroup(int groupPosition) {
return mList.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return mList.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 false;
}
//父列表优化
@Override
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
GroupHodler hodler;
if (convertView == null){
convertView = View.inflate(parent.getContext(),R.layout.cart2_group_item,null);
hodler = new GroupHodler();
hodler.checkBox = convertView.findViewById(R.id.checkBox);
convertView.setTag(hodler);
}else{
hodler = (GroupHodler)convertView.getTag();
}
final Shop shop = mList.get(groupPosition);
hodler.checkBox.setText(shop.getSellerName());
hodler.checkBox.setChecked(shop.isCheck());//设置商铺选中状态
hodler.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
shop.setCheck(isChecked);//数据更新
List goodsList = mList.get(groupPosition).getList();//得到商品信息
for (int i = 0; i < goodsList.size(); i++) {//商品信息循环赋值
goodsList.get(i).setSelected(isChecked?1:0);//商铺选中则商品必须选中
}
notifyDataSetChanged();
//计算价格
calculatePrice();
}
});
return convertView;
}
//价格计算
private void calculatePrice() {
double totalPrice=0;
for (int i = 0; i < mList.size(); i++) {//循环的商家
Shop shop = mList.get(i);
for (int j = 0; j < shop.getList().size(); j++) {
Goods goods = shop.getList().get(j);
if (goods.getSelected()==1) {//如果是选中状态
totalPrice = totalPrice + goods.getNum() * goods.getPrice();
}
}
}
if (totalPriceListener!=null)
totalPriceListener.totalPrice(totalPrice);
}
//子列表优化
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
MyHolder holder;
if (convertView == null){
convertView = View.inflate(parent.getContext(),R.layout.cart_item,null);
holder = new MyHolder();
holder.text = convertView.findViewById(R.id.text);
holder.price = convertView.findViewById(R.id.text_price);
holder.image = convertView.findViewById(R.id.image);
holder.addSub = convertView.findViewById(R.id.add_sub_layout);
holder.check = convertView.findViewById(R.id.cart_goods_check);
convertView.setTag(holder);
}else{
holder = (MyHolder) convertView.getTag();
}
final Goods goods = mList.get(groupPosition).getList().get(childPosition);
holder.text.setText(goods.getTitle());
holder.price.setText("单价:"+goods.getPrice());//单价
//点击选中,计算价格
holder.check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
goods.setSelected(isChecked?1:0);
calculatePrice();//计算价格
}
});
//
if (goods.getSelected()==0){
holder.check.setChecked(false);
}else{
holder.check.setChecked(true);
}
String imageurl = "https" + goods.getImages().split("https")[1];
imageurl = imageurl.substring(0, imageurl.lastIndexOf(".jpg") + ".jpg".length());
Glide.with(DTApplication.getInstance()).load(imageurl).into(holder.image);//加载图片
holder.addSub.setCount(goods.getNum());//设置商品数量
holder.addSub.setAddSubListener(new AddSubLayout.AddSubListener() {
@Override
public void addSub(int count) {
goods.setNum(count);
calculatePrice();//计算价格
}
});
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
//接口回调给Activity页面显示价格刷新
public interface TotalPriceListener{
void totalPrice(double totalPrice);
}
//添加全部对象
public void addAll(List data) {
if (data!=null){
mList.addAll(data);
}
}
/**
*全部选中功能
* @param isCheck
*/
public void checkAll(boolean isCheck) {
for (int i = 0; i < mList.size(); i++) {//循环的商家
Shop shop = mList.get(i);
shop.setCheck(isCheck);
for (int j = 0; j < shop.getList().size(); j++) {
Goods goods = shop.getList().get(j);
goods.setSelected(isCheck?1:0);
}
}
notifyDataSetChanged();
//刷新价格
calculatePrice();
}
//父框件仅仅包含checkbox
class GroupHodler {
CheckBox checkBox;
}
//子框件 (一个复选框 ,, 文字 ,, 价格 ,, 图片 ,, 还有自定义一个类)
class MyHolder{
CheckBox check;
TextView text;
TextView price;
ImageView image;
AddSubLayout addSub;
}
}
bean类构造
Goods
public class Goods implements Serializable {
// "bargainPrice": 111.99,
// "createtime": "2017-10-14T21:39:05",
// "detailUrl": "https:\/\/item.m.jd.com\/product\/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends",
// "images": "https:\/\/m.360buyimg.com\/n0\/jfs\/t9004\/210\/1160833155\/647627\/ad6be059\/59b4f4e1N9a2b1532.jpg!q70.jpg|https:\/\/m.360buyimg.com\/n0\/jfs\/t7504\/338\/63721388\/491286\/f5957f53\/598e95f1N7f2adb87.jpg!q70.jpg|https:\/\/m.360buyimg.com\/n0\/jfs\/t7441\/10\/64242474\/419246\/adb30a7d\/598e95fbNd989ba0a.jpg!q70.jpg",
// "itemtype": 1,
// "pid": 1,
// "price": 118.0,
// "pscid": 1,
// "salenum": 0,
// "sellerid": 17,
// "subhead": "每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下",
// "title": "北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"
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 int count=1;
public void setCount(int count) {
this.count = count;
}
public int getCount() {
return count;
}
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;
}
}
Result
public class Result {
int code;
String msg;
T data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
Shop
public class Shop {
List list;
String sellerName;
String sellerid;
int textColor = 0xffffffff;
int background = R.color.grayblack;
boolean check;
public void setTextColor(int textColor) {
this.textColor = textColor;
}
public int getTextColor() {
return textColor;
}
public void setBackground(int background) {
this.background = background;
}
public int getBackground() {
return background;
}
public void setCheck(boolean check) {
this.check = check;
}
public boolean isCheck() {
return check;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
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;
}
}