简单的RecyclerView嵌套RecyclerView实现购物车效果
今天趁着有空,记录一下在程序中利用RecyclerView嵌套RecyclerView实现的一个购物车功能。
效果如图
勾选与取消勾选都做了相关处理。
首先是首页的布局文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/gray" > <android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/b2c_shop_cart_recyclerView" android:background="#999" android:layout_marginBottom="70dp" android:paddingTop="20dp" > </android.support.v7.widget.RecyclerView> <LinearLayout android:layout_width="match_parent" android:layout_height="70dp" android:orientation="horizontal" android:layout_alignParentBottom="true" android:background="#fff" android:gravity="center_vertical" > <RadioButton android:layout_width="wrap_content" android:layout_height="match_parent" android:textSize="16sp" android:text="全选" android:id="@+id/b2c_shop_all_radiobutton" android:button="@null" android:drawableLeft="@drawable/shop_cart_all_select_bg" android:drawablePadding="5dp" android:layout_marginLeft="50dp" android:padding="10dp" /> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center_vertical" android:text="管理" android:layout_marginLeft="80dp" android:textSize="18sp" android:padding="10dp" android:id="@+id/b2c_shop_manage" /> <View android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" /> <Button android:layout_width="240dp" android:layout_height="match_parent" android:layout_gravity="right" android:text="结算(¥0)" android:textSize="20sp" android:textColor="#fff" android:background="#00a6f2" android:id="@+id/b2c_shop_ok" /> </LinearLayout> </RelativeLayout>首页的activity代码
import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.TextView; import com.google.gson.Gson; import com.hykd.businessapp.R; import com.hykd.businessapp.adapter.MallShopCartBusinessAdapter; import com.hykd.businessapp.api.TestApi; import com.hykd.businessapp.bean.MallShopCartBean; import com.hykd.businessapp.bean.UpdataButton; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.Callback; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.List; import okhttp3.Call; import okhttp3.Response; /** * Created by Administrator on 2017/12/28 0028. */ public class B2cShopCart extends Activity { RecyclerView recyclerView; MallShopCartBusinessAdapter mallShopCartAdapter; RadioButton radioButton; boolean isselect=false; TextView b2c_shop_manage; Button b2c_shop_ok; MallShopCartBean shopCart2Beans2; List<MallShopCartBean.Data> data; String allprice="0"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_b2c_shop_cart); EventBus.getDefault().register(this); recyclerView=findViewById(R.id.b2c_shop_cart_recyclerView); b2c_shop_manage=findViewById(R.id.b2c_shop_manage); b2c_shop_ok=findViewById(R.id.b2c_shop_ok); radioButton=findViewById(R.id.b2c_shop_all_radiobutton); //初始化数据 initData(); //管理按钮的点击时间监听,切换管理跟删除文字以及按钮文字 b2c_shop_manage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(b2c_shop_manage.getText().toString().equals("管理")){ b2c_shop_manage.setText("完成"); b2c_shop_ok.setText("删除"); allprice="0"; b2c_shop_ok.setBackgroundResource(R.drawable.shop_cart_delete_button_bg); b2c_shop_ok.setTextColor(Color.parseColor("#00a0e9")); }else { b2c_shop_manage.setText("管理"); b2c_shop_ok.setText("结算(¥"+allprice+")"); b2c_shop_ok.setBackgroundColor(Color.parseColor("#00a6f2")); b2c_shop_ok.setTextColor(Color.parseColor("#ffffff")); } } }); //全选按钮点击事件监听,连带改变recyclerView中item的选中状态。 radioButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(isselect){ radioButton.setChecked(false); isselect=false; mallShopCartAdapter.setAllselect(false); }else { radioButton.setChecked(true); isselect=true; mallShopCartAdapter.setAllselect(true); } } }); //点击结算按钮的事件监听。 b2c_shop_ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(b2c_shop_ok.getText().toString().equals("删除")){ //这里删除列表中的商品 deleteProduct(); }else { //这里进入结算界面 } } }); } //这里是adapter中的点击事件回调,我这个项目中没用上,还是写出来。 public MallShopCartBusinessAdapter.OnRecyclerViewItemClickListener onRecyclerViewItemClickListener=new MallShopCartBusinessAdapter.OnRecyclerViewItemClickListener() { @Override public void onItemClick(View view, MallShopCartBean.Data data) { } }; private void deleteProduct(){ String deleteid=mallShopCartAdapter.getDeleteProductID(); OkHttpUtils.get().url(TestApi.jianan+TestApi.deleteProduct) .addParams("ids",deleteid) .build() .execute(new Callback() { @Override public Object parseNetworkResponse(Response response, int id) throws Exception { return null; } @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(Object response, int id) { initData(); } }); } private void initData(){ //测试用的数据转换成实体类,赋值到adapter中 String jsonData="{\"code\":200,\"data\":[{\"sellerId\":1,\"cartItemResultDtoList\":[{\"mainImg\":\"http://imglib.medrd.com/group1/M00/00/02/CthJHVpgYPyAXGBjAACn6upITiQ992.jpg\",\"quantity\":1,\"sellerName\":\"华医B2C旗舰店\",\"goodId\":9,\"goodPrice\":\"0.01\",\"fullCutResultDtos\":[],\"goodImg\":\"M00/00/02/CthJHVpgYPyAXGBjAACn6upITiQ992.jpg\",\"sellerId\":1,\"goodName\":\"百草味牛肉条(五香味)1...\",\"specificationValues\":[{\"active\":1,\"created\":\"2018-01-29 16:43:45\",\"id\":28,\"image\":null,\"name\":\"100g\",\"orders\":3,\"seller_id\":1,\"specification_id\":5,\"updated\":\"2018-01-29 16:43:45\"}],\"id\":505,\"stock\":94,\"selected\":true},{\"mainImg\":\"http://imglib.medrd.com/group1/M00/00/02/CthJHVplO7SAE4jWAAEaatjcfgQ285.jpg\",\"quantity\":2,\"sellerName\":\"华医B2C旗舰店\",\"goodId\":21,\"goodPrice\":\"99\",\"fullCutResultDtos\":[],\"goodImg\":\"M00/00/02/CthJHVplO7SAE4jWAAEaatjcfgQ285.jpg\",\"sellerId\":1,\"goodName\":\"蓝月亮洗衣液套装2kg瓶...\",\"specificationValues\":[],\"id\":506,\"stock\":150,\"selected\":true}],\"sellerName\":\"华医B2C旗舰店\"}],\"Success\":true}"; Gson gson = new Gson(); shopCart2Beans2=gson.fromJson(jsonData,MallShopCartBean.class); data=null; data=shopCart2Beans2.getData(); if(mallShopCartAdapter!=null){ mallShopCartAdapter.setmDatas(data); mallShopCartAdapter.notifyDataSetChanged(); }else { mallShopCartAdapter=new MallShopCartBusinessAdapter(B2cShopCart.this,data); recyclerView.setLayoutManager(new LinearLayoutManager(B2cShopCart.this,LinearLayoutManager.VERTICAL,false)); recyclerView.setAdapter(mallShopCartAdapter); mallShopCartAdapter.setOnItemClickListener(onRecyclerViewItemClickListener); } // OkHttpUtils.get().url(TestApi.jianan+TestApi.getShopCartGoodsL) // .addParams("buyerId",2+"") // .build() // .execute(new Callback() { // @Override // public MallShopCartBean parseNetworkResponse(Response response, int id) throws Exception { // String string = response.body().string(); // Log.d("MallShopCartBean===",string); // MallShopCartBean user = new Gson().fromJson(string, MallShopCartBean.class); // return user; // } // // @Override // public void onError(Call call, Exception e, int id) { // Toast.makeText(B2cShopCart.this, "服务异常!", Toast.LENGTH_SHORT).show(); // } // // @Override // public void onResponse(Object response, int id) { // // shopCart2Beans2=(MallShopCartBean)response; // data=null; // data=shopCart2Beans2.getData(); // if(mallShopCartAdapter!=null){ // mallShopCartAdapter.setmDatas(data); // mallShopCartAdapter.notifyDataSetChanged(); // }else { // mallShopCartAdapter=new MallShopCartBusinessAdapter(B2cShopCart.this,data); // recyclerView.setLayoutManager(new LinearLayoutManager(B2cShopCart.this,LinearLayoutManager.VERTICAL,false)); // recyclerView.setAdapter(mallShopCartAdapter); // mallShopCartAdapter.setOnItemClickListener(onRecyclerViewItemClickListener); // } // // } // }); } //这里用了eventBus来进行实时价格的UI更改。 @Subscribe(threadMode = ThreadMode.MAIN) public void messageEventBus(UpdataButton event){ //刷新UI if(!b2c_shop_ok.getText().toString().equals("删除")){ b2c_shop_ok.setText("结算(¥"+event.getAllPrice()+")"); allprice=event.getAllPrice(); } } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } }MallShopCartBean
import java.math.BigDecimal; import java.util.List; /** * Created by Administrator on 2018/1/9 0009. */ public class MallShopCartBean implements Cloneable{ Integer code; Boolean Success; List<Data> data; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public Boolean getSuccess() { return Success; } public void setSuccess(Boolean success) { Success = success; } public List<Data> getData() { return data; } public void setData(List<Data> data) { this.data = data; } public class Data{ Integer sellerId; String sellerName; List<CartItemResultDtoList> cartItemResultDtoList; boolean isChecked; public boolean isChecked() { return isChecked; } public void setChecked(boolean checked) { isChecked = checked; } public Integer getSellerId() { return sellerId; } public void setSellerId(Integer sellerId) { this.sellerId = sellerId; } public String getSellerName() { return sellerName; } public void setSellerName(String sellerName) { this.sellerName = sellerName; } public List<CartItemResultDtoList> getCartItemResultDtoList() { return cartItemResultDtoList; } public void setCartItemResultDtoList(List<CartItemResultDtoList> cartItemResultDtoList) { this.cartItemResultDtoList = cartItemResultDtoList; } public class CartItemResultDtoList{ String mainImg; Integer quantity; String goodName; Integer id; Integer goodId; Integer stock; BigDecimal goodPrice; List<SpecificationValues> specificationValues; boolean isChecked; public boolean isChecked() { return isChecked; } public void setChecked(boolean checked) { isChecked = checked; } public String getMainImg() { return mainImg; } public void setMainImg(String mainImg) { this.mainImg = mainImg; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public String getGoodName() { return goodName; } public void setGoodName(String goodName) { this.goodName = goodName; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getGoodId() { return goodId; } public void setGoodId(Integer goodId) { this.goodId = goodId; } public Integer getStock() { return stock; } public void setStock(Integer stock) { this.stock = stock; } public BigDecimal getGoodPrice() { return goodPrice; } public void setGoodPrice(BigDecimal goodPrice) { this.goodPrice = goodPrice; } public List<SpecificationValues> getSpecificationValues() { return specificationValues; } public void setSpecificationValues(List<SpecificationValues> specificationValues) { this.specificationValues = specificationValues; } public class SpecificationValues{ Integer id; String name; Integer specification_id; Integer active; Integer orders; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSpecification_id() { return specification_id; } public void setSpecification_id(Integer specification_id) { this.specification_id = specification_id; } public Integer getActive() { return active; } public void setActive(Integer active) { this.active = active; } public Integer getOrders() { return orders; } public void setOrders(Integer orders) { this.orders = orders; } @Override public String toString() { return "SpecificationValues{" + "id=" + id + ", name='" + name + '\'' + ", specification_id=" + specification_id + ", active=" + active + ", orders=" + orders + '}'; } } @Override public String toString() { return "CartItemResultDtoList{" + "mainImg='" + mainImg + '\'' + ", quantity=" + quantity + ", goodName='" + goodName + '\'' + ", id=" + id + ", goodId=" + goodId + ", stock=" + stock + ", goodPrice=" + goodPrice + ", specificationValues=" + specificationValues + ", isChecked=" + isChecked + '}'; } } @Override public String toString() { return "Data{" + "sellerId=" + sellerId + ", sellerName='" + sellerName + '\'' + ", cartItemResultDtoList=" + cartItemResultDtoList + ", isChecked=" + isChecked + '}'; } } @Override public String toString() { return "MallShopCart2Bean{" + "code=" + code + ", Success=" + Success + ", data=" + data + '}'; } }
item_mall_shop_cart_business_list.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="wrap_content" android:orientation="vertical" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginBottom="15dp" android:background="#fff" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:id="@+id/item_layout" android:gravity="center" android:visibility="gone" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/itme_text1" android:textSize="25sp" android:text="test11111" android:gravity="center" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/itme_text2" android:textSize="25sp" android:text="test2222" android:layout_marginTop="20dp" android:gravity="center" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:gravity="center_vertical" > <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:button="@drawable/shop_cart_all_select_bg" android:id="@+id/item_mall_shop_cart_businessname_select" android:padding="10dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="XXX旗舰店" android:textSize="20sp" android:drawableRight="@mipmap/arrows_right" android:drawablePadding="10dp" android:id="@+id/item_mall_shop_cart_businessname" android:layout_marginTop="15dp" android:layout_marginBottom="15dp" /> </LinearLayout> <android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/item_mall_shop_cart_recyclerview" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" > </android.support.v7.widget.RecyclerView> </LinearLayout>
MallShopCartBusinessAdapter
import android.content.Context; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import com.hykd.businessapp.R; import com.hykd.businessapp.bean.MallShopCartBean; import com.hykd.businessapp.bean.UpdataButton; import org.greenrobot.eventbus.EventBus; import java.math.BigDecimal; import java.util.List; /** * Created by Administrator on 2017/12/28 0028. */ public class MallShopCartBusinessAdapter extends RecyclerView.Adapter<MallShopCartBusinessAdapter.MyViewHolder> implements View.OnClickListener{ private Context mContext; private List<MallShopCartBean.Data> mDatas; private LayoutInflater inflater; private OnRecyclerViewItemClickListener onItemClickListener; MallShopCartProductAdapter mallShopCartAdapter; private boolean isselect=false; int pos=0; public MallShopCartBusinessAdapter(Context context, List<MallShopCartBean.Data> cartBeans){ this. mContext=context; this. mDatas=cartBeans; inflater= LayoutInflater.from(mContext); // flag=new boolean[jsonArray.length()]; // zflag=new boolean[jsonArray.length()]; } //返回item布局 @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.item_mall_shop_cart_business_list,parent, false); MyViewHolder holder= new MyViewHolder(view); view.setOnClickListener(this); return holder; } @Override public void onBindViewHolder(final MallShopCartBusinessAdapter.MyViewHolder holder, int position) { final MallShopCartBean.Data cartBean = mDatas.get(position); holder.bussinessname.setText(cartBean.getSellerName()); holder.checkBox.setOnCheckedChangeListener(null); //读取实体内存储的选中状态 holder.checkBox.setChecked(cartBean.isChecked()); holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { //更改item选中状态同时进行实体内的选中状态改变 cartBean.setChecked(isChecked); // flag[position]=isChecked; //外层选中状态改变后,要遍历改变子recyclerView内item的选中状态 for (MallShopCartBean.Data.CartItemResultDtoList cartItemResultDtoList : cartBean.getCartItemResultDtoList()){ cartItemResultDtoList.setChecked(isChecked); } notifyDataSetChanged(); EventBus.getDefault().post(new UpdataButton(getAllPrice())); } }); holder.itemView.setTag(cartBean);//传object回去 //单个商家的商品列表不需要滑动,所以在这里禁止掉商品item的滑动事件 LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL, false) { @Override public boolean canScrollVertically() { return false; } }; //这里是初始化商品item的recyclerView,将外层实例传入子层以便刷新 mallShopCartAdapter=new MallShopCartProductAdapter(mContext,cartBean.getCartItemResultDtoList(),cartBean,this); holder.recyclerView.setLayoutManager(linearLayoutManager); holder.recyclerView.setAdapter(mallShopCartAdapter); //下面两句是防止刷新商品的recyclerView导致商家recyclerView也发生滑动 holder.recyclerView.setFocusableInTouchMode(false); holder.recyclerView.requestFocus(); } @Override public int getItemCount() { return mDatas.size(); } @Override public long getItemId(int position) { return position; } @Override public void onClick(View v) { if (onItemClickListener != null) { //注意这里使用getTag方法获取数据 onItemClickListener.onItemClick(v,(MallShopCartBean.Data) v.getTag()); } } class MyViewHolder extends RecyclerView.ViewHolder { TextView bussinessname; CheckBox checkBox; RecyclerView recyclerView; public MyViewHolder(View view) { super(view); bussinessname=view.findViewById(R.id.item_mall_shop_cart_businessname); checkBox=view.findViewById(R.id.item_mall_shop_cart_businessname_select); recyclerView=view.findViewById(R.id.item_mall_shop_cart_recyclerview); } } public interface OnRecyclerViewItemClickListener { void onItemClick(View view , MallShopCartBean.Data data); } public void setOnItemClickListener(OnRecyclerViewItemClickListener listener) { this.onItemClickListener = listener; } //设置全选/全不选 public void setAllselect(boolean b){ for(int i=0;i<mDatas.size();i++){ mDatas.get(i).setChecked(b); for (MallShopCartBean.Data.CartItemResultDtoList cartItemResultDtoList : mDatas.get(i).getCartItemResultDtoList()){ cartItemResultDtoList.setChecked(b); } } notifyDataSetChanged(); EventBus.getDefault().post(new UpdataButton(getAllPrice())); } public String getSelectTitle(){ StringBuffer stringBuffer=new StringBuffer(); if(mDatas!=null){ for (int i=0;i<mDatas.size();i++){ List<MallShopCartBean.Data.CartItemResultDtoList> data=mDatas.get(i).getCartItemResultDtoList(); for (int y=0;y<data.size();y++){ if(data.get(y).isChecked()){ stringBuffer.append(data.get(y).getGoodName()); if(y<data.size()-1){ stringBuffer.append(","); } } } } } return stringBuffer.toString(); } //获取需要删除的商品id public String getDeleteProductID(){ StringBuffer stringBuffer=new StringBuffer(); if(mDatas!=null){ for (int i=0;i<mDatas.size();i++){ List<MallShopCartBean.Data.CartItemResultDtoList> data=mDatas.get(i).getCartItemResultDtoList(); for (int y=0;y<data.size();y++){ if(data.get(y).isChecked()){ stringBuffer.append(data.get(y).getId()); if(y<data.size()-1){ stringBuffer.append("#"); } } } } } return stringBuffer.toString(); } public void setmDatas( List<MallShopCartBean.Data> mDatas){ this.mDatas=mDatas; } //获取需要商品总价格 public String getAllPrice(){ BigDecimal allprice =new BigDecimal("0"); if(mDatas!=null){ for (int i=0;i<mDatas.size();i++){ List<MallShopCartBean.Data.CartItemResultDtoList> data=mDatas.get(i).getCartItemResultDtoList(); for (int y=0;y<data.size();y++){ if(data.get(y).isChecked()){ System.out.println(data.get(y).getGoodPrice()+"getGoodPrice"); BigDecimal interestRate = new BigDecimal(data.get(y).getQuantity()); BigDecimal interest = data.get(y).getGoodPrice().multiply(interestRate); allprice=allprice.add(interest); System.out.println(allprice+"allprice"+interest+"interestRate"+interestRate); } } } } return allprice.toString(); } }
item_mall_shop_cart_product_list.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="164dp" android:orientation="vertical" > <View android:layout_width="match_parent" android:layout_height="1dp" android:background="#b2b2b2" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:layout_marginRight="20dp" > <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:button="@drawable/shop_cart_all_select_bg" android:layout_marginLeft="20dp" android:id="@+id/item_mall_shop_cart_list_checkbox" android:padding="10dp" /> <ImageView android:layout_width="140dp" android:layout_height="140dp" android:layout_marginTop="12dp" android:layout_marginBottom="12dp" android:layout_marginRight="20dp" android:id="@+id/item_mall_shop_cart_list_iamgeview" android:scaleType="centerCrop" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_weight="1" android:layout_gravity="center_vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20sp" android:id="@+id/item_mall_shop_cart_list_title" android:layout_marginTop="10dp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" android:layout_marginTop="12dp" android:textColor="#999" android:id="@+id/item_mall_shop_cart_list_pecification" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="24sp" android:layout_marginTop="32dp" android:textColor="#f00" android:id="@+id/item_mall_shop_cart_list_price" /> </LinearLayout> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:src="@mipmap/minus_button" android:id="@+id/item_mall_shop_cart_list_minus_button" /> <TextView android:layout_width="100dp" android:layout_height="40dp" android:layout_gravity="center_vertical" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:text="1" android:gravity="center" android:textSize="18sp" android:id="@+id/item_mall_shop_cart_list_number" android:background="@drawable/shop_cart_number_text_bg" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:src="@mipmap/add_button" android:id="@+id/item_mall_shop_cart_list_add_button" /> </LinearLayout> </LinearLayout>
MallShopCartProductAdapter
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.hykd.businessapp.R; import com.hykd.businessapp.bean.MallShopCartBean; import com.hykd.businessapp.bean.UpdataButton; import org.greenrobot.eventbus.EventBus; import java.util.List; /** * Created by Administrator on 2017/12/28 0028. */ public class MallShopCartProductAdapter extends RecyclerView.Adapter<MallShopCartProductAdapter.MyViewHolder> implements View.OnClickListener{ private Context mContext; private List<MallShopCartBean.Data.CartItemResultDtoList> mDatas; private LayoutInflater inflater; private OnRecyclerViewItemClickListener onItemClickListener; MallShopCartBean.Data bean; MallShopCartBusinessAdapter mallShopCartAdapter2; public MallShopCartProductAdapter(Context context, List<MallShopCartBean.Data.CartItemResultDtoList> jsonArray, MallShopCartBean.Data bean, MallShopCartBusinessAdapter mallShopCartAdapter2){ this. mContext=context; this. mDatas=jsonArray; this.bean=bean; this.mallShopCartAdapter2=mallShopCartAdapter2; inflater= LayoutInflater.from(mContext); } //返回item布局 @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.item_mall_shop_cart_product_list,parent, false); MyViewHolder holder= new MyViewHolder(view); view.setOnClickListener(this); return holder; } @Override public long getItemId(int position) { return position; } @Override public void onBindViewHolder(final MallShopCartProductAdapter.MyViewHolder holder, final int position) { final MallShopCartBean.Data.CartItemResultDtoList cartBean = mDatas.get(position); holder.item_mall_shop_cart_list_title.setText(cartBean.getGoodName()); holder.checkBox.setOnCheckedChangeListener(null); //读取实体内存储的选中状态 holder.checkBox.setChecked(cartBean.isChecked()); holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // flag[position]=isChecked; //更改item选中状态同时进行实体内的选中状态改变 cartBean.setChecked(isChecked); boolean noSelect=false; //内层item选中状态改变后要遍历判断是否全选,以改变外层item的选中状态 for(MallShopCartBean.Data.CartItemResultDtoList cartItemResultDtoList :mDatas){ if(!cartItemResultDtoList.isChecked()){ noSelect=true; } } if(!noSelect){ bean.setChecked(!noSelect); mallShopCartAdapter2.notifyDataSetChanged(); }else{ bean.setChecked(!noSelect); mallShopCartAdapter2.notifyDataSetChanged(); } EventBus.getDefault().post(new UpdataButton(mallShopCartAdapter2.getAllPrice())); } }); holder.item_mall_shop_cart_list_number.setText(mDatas.get(position).getQuantity()+""); holder.item_mall_shop_cart_list_add_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int number=Integer.valueOf(holder.item_mall_shop_cart_list_number.getText().toString()); if(number<mDatas.get(position).getStock()){ number++; mDatas.get(position).setQuantity(number); EventBus.getDefault().post(new UpdataButton(mallShopCartAdapter2.getAllPrice())); holder.item_mall_shop_cart_list_number.setText(number+""); }else { Toast.makeText(mContext, "已经是最大库存量!", Toast.LENGTH_SHORT).show(); } } }); holder.item_mall_shop_cart_list_minus_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int number=Integer.valueOf(holder.item_mall_shop_cart_list_number.getText().toString()); if(number>1){ number--; mDatas.get(position).setQuantity(number); EventBus.getDefault().post(new UpdataButton(mallShopCartAdapter2.getAllPrice())); holder.item_mall_shop_cart_list_number.setText(number+""); }else { Toast.makeText(mContext, "已经是最少数量!", Toast.LENGTH_SHORT).show(); } } }); holder.item_mall_shop_cart_list_price.setText("¥"+mDatas.get(position).getGoodPrice()+""); StringBuffer stringBuffer=new StringBuffer(); List<MallShopCartBean.Data.CartItemResultDtoList.SpecificationValues> list=mDatas.get(position).getSpecificationValues(); for (int i=0;i<list.size();i++){ stringBuffer.append(list.get(i).getName()); if(i<list.size()-1){ stringBuffer.append(","); } } holder.item_mall_shop_cart_list_pecification.setText("规格:"+stringBuffer); Glide.with(mContext).load("http://res.medrd.com/pic/2017/12/b124badaa47347ec8bd3d50f152e2d6b.png").into(holder.item_mall_shop_cart_list_iamgeview); holder.itemView.setTag(mDatas.get(position));//传object回去 } @Override public int getItemCount() { return mDatas.size(); } @Override public void onClick(View v) { if (onItemClickListener != null) { //注意这里使用getTag方法获取数据 onItemClickListener.onItemClick(v,(MallShopCartBean.Data.CartItemResultDtoList) v.getTag()); } } class MyViewHolder extends RecyclerView.ViewHolder { ImageView item_mall_shop_cart_list_iamgeview; CheckBox checkBox; TextView item_mall_shop_cart_list_title,item_mall_shop_cart_list_pecification,item_mall_shop_cart_list_price,item_mall_shop_cart_list_number; ImageView item_mall_shop_cart_list_minus_button,item_mall_shop_cart_list_add_button; public MyViewHolder(View view) { super(view); checkBox=view.findViewById(R.id.item_mall_shop_cart_list_checkbox); item_mall_shop_cart_list_iamgeview=view.findViewById(R.id.item_mall_shop_cart_list_iamgeview); item_mall_shop_cart_list_title =view.findViewById(R.id.item_mall_shop_cart_list_title); item_mall_shop_cart_list_pecification =view.findViewById(R.id.item_mall_shop_cart_list_pecification); item_mall_shop_cart_list_price =view.findViewById(R.id.item_mall_shop_cart_list_price); item_mall_shop_cart_list_minus_button=view.findViewById(R.id.item_mall_shop_cart_list_minus_button); item_mall_shop_cart_list_add_button=view.findViewById(R.id.item_mall_shop_cart_list_add_button); item_mall_shop_cart_list_number=view.findViewById(R.id.item_mall_shop_cart_list_number); } } public interface OnRecyclerViewItemClickListener { void onItemClick(View view , MallShopCartBean.Data.CartItemResultDtoList data); } public void setOnItemClickListener(OnRecyclerViewItemClickListener listener) { this.onItemClickListener = listener; } public void setAllselect(boolean b){ for(int i=0;i<mDatas.size();i++){ mDatas.get(i).setChecked(b); } } }这样就差不多了,刷新ui用的eventBus这个库感觉比广播好用很多,推荐大家用
compile 'org.greenrobot:eventbus:3.0.0'
demo里用的网络请求是
compile 'com.zhy:okhttputils:2.6.2'
gson解析库
compile 'com.google.code.gson:gson:2.8.2'
图片加载库
compile 'com.github.bumptech.glide:glide:4.0.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0'
代码也不复杂,重要的地方都加了注释,基本能满足普通的购物车需求,可能有部分逻辑有点问题,需要你们自己在测试的时候去优化,毕竟只是demo没考虑很全,其实最容易出问题的地方是在选中跟没选中的处理上,我是在实体内加了一个boolean,用来记录选中状态,目前项目的购物车数据是存在后台数据库,所以列表需要网络请求获取,相关操作也要请求网络,如果你们的项目中购物车没有写在后台,商品数据可以存本地数据库,从本地数据库读取购物车的商品列表,增删改都直接本地操作比较性能会比较好。