模仿京东购物车MVP模式

xiaoxiao2021-02-28  15

1.首先把权限三部曲写好

<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 2.根据个人需要导入依赖

compile 'com.github.bumptech.glide:glide:4.0.0' compile 'com.squareup.okhttp:okhttp:2.4.0' compile 'com.google.code.gson:gson:2.8.1' 3.写你的mainactivityLayout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:background="#ff55"> <ImageView android:layout_width="60dp" android:layout_height="wrap_content" android:src="@drawable/back" android:layout_weight="1" android:id="@+id/backbut"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="购物车" android:textSize="26dp" android:layout_weight="1" android:gravity="center_horizontal"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="编辑" android:textSize="16dp" android:layout_weight="1" android:gravity="center_horizontal" android:id="@+id/edit_tvshow"/> </LinearLayout> <ExpandableListView android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:id="@+id/exp_viewshow"> </ExpandableListView> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#f565ff"> <CheckBox android:layout_width="80dp" android:layout_height="wrap_content" android:text="全选" android:id="@+id/checkboxs" android:layout_weight="1"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="合计:¥00.00" android:id="@+id/amount" android:layout_weight="1" android:textSize="18dp"/> <TextView android:layout_width="wrap_content" android:layout_height="50dp" android:text="去结算(0)" android:textSize="22dp" android:textColor="#fff" android:layout_weight="1" android:gravity="center" android:id="@+id/accounts" android:background="#ff22"/> </LinearLayout> </LinearLayout> 4.将MVP包分好

(1)view层→activity→adapter→fargment

(2)model层→model层接口(名字自定义)→model类(名字自定义)

(3)presenter层→presenter层接口(名字自定义)→presenter类(名自定义)

注意接口必须实现

5.bean包里的MyShoppingBean类

为了节省空间,我直接写我个人用户请求的链接地址,bean类内容自己请求

(1)http://120.27.23.105/user/login?mobile=15800002222&password=123456  登录链接地址

(2)http://120.27.23.105/product/getCarts?uid=10152&source=android     查询购物车链接地址

//商家是否被选中 组条目是否被选中 private boolean isGroupChoosed; public boolean isGroupChoosed() { return isGroupChoosed; } public void setGroupChoosed(boolean groupChoosed) { isGroupChoosed = groupChoosed; }

//子条目商品是否被选中的一个字段状态 private boolean isChildChoosed; public boolean isChildChoosed() { return isChildChoosed; } public void setChildChoosed(boolean childChoosed) { isChildChoosed = childChoosed; }

6.model层里的InShoppingModel接口(此接口有一个getCarInfo方法,方法里有两个属性,第一个是用户ID,第二个是prersenter层InShoppingPrersenter接口,用来与p层沟通)

public interface InShoppingModel { void getCarInfo(String uid,InShoppingPresenter inShoppingPresenter); } 7.model层里的ShoppingModel类(此类用来写数据编辑、数据逻辑、网络请求。。。)

public class ShoppingModel implements InShoppingModel{ private static Handler handler = new Handler(); @Override public void getCarInfo(String uid, final InShoppingPresenter inShoppingPresenter) { //创建OkHttpClient对象 OkHttpClient okHttpClient = new OkHttpClient(); final Request request = new Request.Builder() .get() .url("http://120.27.23.105/product/getCarts?uid="+uid+"&source=android") .build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { private MyShoppingBean myShoppingBean; @Override public void onFailure(final Request request, final IOException e) { handler.post(new Runnable() { @Override public void run() { inShoppingPresenter.onFailed(e.getMessage()); } }); } @Override public void onResponse(Response response) throws IOException { if(response.isSuccessful()){ String result = response.body().string(); Gson gson = new Gson(); myShoppingBean = gson.fromJson(result, MyShoppingBean.class); } handler.post(new Runnable() { @Override public void run() { inShoppingPresenter.onSuccess(myShoppingBean.getData()); } }); } }); } } 8.prersenter层InShoppingPrersenter接口(p层是与M层和V层搭接的桥梁,方法有失败和成功用于M层网络请求成功或失败的,onDestory方法用于内存泄漏做优化,getCarInfo是与M层进行连接)

public interface InShoppingPresenter { void onSuccess(List<MyShoppingBean.DataBean> data); void onFailed(String msg); void onDestory(); void getCarInfo(String uid); } 9.prersenter层ShoppingPrersenter类(MVP最难在与三个层的链接,剩下的我就不解释了,如果还看不懂那就从JAVA接口实现学习吧)

public class Shoppingpresenter implements InShoppingPresenter{ private InShoppingCart inShoppingCart; private InShoppingModel inShoppingModel; public Shoppingpresenter(InShoppingCart inShoppingCart) { this.inShoppingCart = inShoppingCart; inShoppingModel = new ShoppingModel(); } @Override public void onSuccess(List<MyShoppingBean.DataBean> data) { if(inShoppingCart != null){ inShoppingCart.onSuccess(data); } } @Override public void onFailed(String msg) { if(inShoppingCart != null){ inShoppingCart.onFailed(msg); } } @Override public void onDestory() { if(inShoppingCart != null) { inShoppingCart = null; } } @Override public void getCarInfo(String uid) { inShoppingModel.getCarInfo(uid,this); } }

10.view层 activity包里的InShoppingCart类

public interface InShoppingCart { void onSuccess(List<MyShoppingBean.DataBean> data); void onFailed(String msg); void checkGroupItem(int groupPosition, boolean isChecked); //商品的checkbox void checkChildItem(int groupPosition, int childPosition, boolean isChecked); }

11.view层 activity包里的MainActivity

public class MainActivity extends AppCompatActivity implements InShoppingCart, ExpAdapter.ModifyGoodsItemNumberListener, ExpAdapter.CheckGroupItemListener { private ExpandableListView expview; private CheckBox checkbox; private TextView accounts; private TextView edit; private ExpAdapter adapter; private Shoppingpresenter shoppp; //默认是false private boolean flag; private List<MyShoppingBean.DataBean> list; //购买商品的总数量 private int totalNum = 0; //购买商品的总价 private double totalPrice= 0.00; //15.55 15 0.55亿 private TextView amount; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); expview = (ExpandableListView)findViewById(R.id.exp_viewshow); //购物车底部栏的全选框 checkbox = (CheckBox)findViewById(R.id.checkboxs); //合计,计算总价 amount = (TextView) findViewById(R.id.amount); //结算按钮 accounts = (TextView)findViewById(R.id.accounts); //找到编辑控件 edit = (TextView)findViewById(R.id.edit_tvshow); //去除默认指示器 expview.setGroupIndicator(null); //设置适配器 adapter = new ExpAdapter(this); expview.setAdapter(adapter); //获取购物车信息 shoppp = new Shoppingpresenter(this); shoppp.getCarInfo("10152"); //设置商品加减的监听 adapter.setModifyGoodsItemNumberListener(this); //设置商家以及商品是否被选中的监听 adapter.setCheckGroupItemListener(this); // 编辑 edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!flag){//编辑 -> 完成\ flag = true; edit.setText("完成"); adapter.showDeleteButton(flag); }else{ flag = false; edit.setText("编辑"); adapter.showDeleteButton(flag); } } }); } //二级列表默认展开 private void defaultExpand(){ for (int i = 0; i < adapter.getGroupCount();++i){ expview.expandGroup(i); } } @Override public void onSuccess(List<MyShoppingBean.DataBean> data) { this.list = data; //设置数据 adapter.setList(list); defaultExpand(); } @Override public void onFailed(String msg) { } public void doIncrease(int groupPosition, int childPosition, View view) { //Toast.makeText(this, "用户点击了商品添加操作", Toast.LENGTH_SHORT).show(); MyShoppingBean.DataBean.ListBean listBean = list.get(groupPosition).getList().get(childPosition); //取出当前的商品数量 int currentNum = listBean.getNum(); //商品++ currentNum++; //将商品数量设置javabean listBean.setNum(currentNum); //刷新适配器 adapter.notifyDataSetChanged(); //计算商品价格 // statisticsPrice(); }//商家checkbox @Override public void doDecrease(int groupPosition, int childPosition, View view) { MyShoppingBean.DataBean.ListBean listBean = list.get(groupPosition).getList().get(childPosition); //取出当前的商品数量 int currentNum = listBean.getNum(); //直接结束这个方法 if(currentNum == 1){ return; } currentNum--; listBean.setNum(currentNum); //刷新适配器 adapter.notifyDataSetChanged(); //计算商品价格 statisticsPrice(); } @Override public void checkGroupItem(int groupPosition, boolean isChecked) { //Toast.makeText(this, "商家", Toast.LENGTH_SHORT).show(); //商家javabean MyShoppingBean.DataBean dataBean = list.get(groupPosition); dataBean.setGroupChoosed(isChecked); //遍历商家里面的商品,将其置为选中状态 for (MyShoppingBean.DataBean.ListBean listBean : dataBean.getList()){ listBean.setChildChoosed(isChecked); } //底部结算那个checkbox状态(全选) if(isCheckAll()){ checkbox.setChecked(true); }else{ checkbox.setChecked(false); } //刷新适配器 adapter.notifyDataSetChanged(); //计算价格 statisticsPrice(); } //商品的checkbox @Override public void checkChildItem(int groupPosition, int childPosition, boolean isChecked) { //Toast.makeText(this, "商品", Toast.LENGTH_SHORT).show(); //ShoppCarBean.DataBean.ListBean listBean = list.get(groupPosition).getList().get(childPosition); MyShoppingBean.DataBean dataBean = list.get(groupPosition);//商家那一层 List<MyShoppingBean.DataBean.ListBean> listBeans = dataBean.getList(); MyShoppingBean.DataBean.ListBean listBean = listBeans.get(childPosition); //你点击商家的商品条目将其选中状态记录 listBean.setChildChoosed(isChecked); //检测商家里面的每一个商品是否被选中,如果被选中,返回boolean boolean result = isGoodsCheckAll(groupPosition); if(result){ dataBean.setGroupChoosed(result); }else{ dataBean.setGroupChoosed(result); } //底部结算那个checkbox状态(全选) if(isCheckAll()){ checkbox.setChecked(true); }else{ checkbox.setChecked(false); } //刷新适配器 adapter.notifyDataSetChanged(); //计算总价 statisticsPrice(); } /** * 检测某个商家的商品是否都选中,如果都选中的话,商家CheckBox应该是选中状态 * @param groupPosition * @return */ private boolean isGoodsCheckAll(int groupPosition){ List<MyShoppingBean.DataBean.ListBean> listBeans = this.list.get(groupPosition).getList(); //遍历某一个商家的每个商品是否被选中 for (MyShoppingBean.DataBean.ListBean listBean : listBeans){ if(listBean.isChildChoosed()){//是选中状态 continue; }else{ return false; } } return true; } //购物车商品是否全部选中 private boolean isCheckAll(){ for (MyShoppingBean.DataBean dataBean : list){ if(!dataBean.isGroupChoosed()){ return false; } } return true; } //全选与反选 private void isChoosedAll(boolean isChecked){ for (MyShoppingBean.DataBean dataBean : list){ dataBean.setGroupChoosed(isChecked); for (MyShoppingBean.DataBean.ListBean listBean : dataBean.getList()){ listBean.setChildChoosed(isChecked); } } //刷新适配器 adapter.notifyDataSetChanged(); } /** * 计算你所选中的商品总价 */ private void statisticsPrice(){ //初始化值 totalNum = 0; totalPrice = 0.00; for (MyShoppingBean.DataBean dataBean : list){ for (MyShoppingBean.DataBean.ListBean listBean : dataBean.getList()){ if(listBean.isChildChoosed()){ totalNum++; System.out.println("number : "+totalNum); totalPrice += listBean.getNum()*listBean.getPrice(); } } } //设置文本信息 合计、结算的商品数量 amount.setText("合计:"+totalNum); accounts.setText("结算("+totalPrice+")"); } @Override public void onPointerCaptureChanged(boolean hasCapture) { } } 12.Layout包下的layout_expadapter.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <CheckBox android:id="@+id/ck_child_choose" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="5dp" android:scaleX="0.6" android:scaleY="0.6" /> <ImageView android:id="@+id/iv_show_pic" android:layout_width="70dp" android:layout_height="80dp" android:layout_centerVertical="true" android:layout_marginLeft="5dp" android:src="@mipmap/ic_launcher" android:layout_toRightOf="@id/ck_child_choose" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="15dp" android:layout_toRightOf="@id/iv_show_pic" android:orientation="vertical"> <TextView android:id="@+id/tv_commodity_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="酒红色纯红色纯羊毛西服套装" android:textColor="@android:color/black" android:textSize="12sp" android:textStyle="bold" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/tv_commodity_attr" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="3dp" android:text="属性:粉蓝色" android:textSize="12sp" android:textColor="@color/colorPrimary" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="4dp" android:orientation="horizontal"> <TextView android:id="@+id/tv_commodity_price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="390" android:textColor="@android:color/holo_red_dark" android:textSize="12sp" android:textStyle="bold" /> <TextView android:id="@+id/tv_commodity_num" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:text="x1" android:textColor="@android:color/darker_gray" /> <LinearLayout android:id="@+id/rl_edit" android:layout_width="120dp" android:background="@android:color/holo_orange_light" android:layout_height="30dp" android:layout_marginLeft="20dp" > <TextView android:id="@+id/iv_sub" android:layout_width="0dp" android:layout_weight="1" android:gravity="center" android:textColor="@android:color/black" android:background="@android:color/white" android:layout_margin="1dp" android:layout_height="match_parent" android:text=" - " /> <TextView android:id="@+id/tv_commodity_show_num" android:layout_width="0dp" android:layout_weight="1" android:gravity="center" android:background="@android:color/white" android:layout_margin="1dp" android:layout_height="match_parent" android:text="1" /> <TextView android:id="@+id/iv_add" android:layout_width="0dp" android:layout_weight="1" android:gravity="center" android:layout_margin="1dp" android:background="@android:color/white" android:layout_height="match_parent" android:text=" + " /> </LinearLayout> </LinearLayout> </LinearLayout> <Button android:id="@+id/btn_commodity_delete" android:layout_width="30dp" android:layout_height="30dp" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:gravity="center" android:text="x" android:background="@android:color/holo_blue_light" android:textSize="20sp" android:textColor="@android:color/holo_green_dark" android:layout_margin="5dp" android:visibility="gone" /> </RelativeLayout> 13.Layout包下的layout_group.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <CheckBox android:id="@+id/ck_group_choosed" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="商家1" android:gravity="center_vertical" android:textSize="25sp" android:focusable="false" android:padding="10dp"/> </LinearLayout>

14.view层adapter包里的ExpAdapter类

public class ExpAdapter extends BaseExpandableListAdapter { private final MainActivity mainActivity; private List<MyShoppingBean.DataBean> data; private ModifyGoodsItemNumberListener modifyGoodsItemNumberListener; private CheckGroupItemListener checkGroupItemListener; private boolean edit; public ExpAdapter(MainActivity mainActivity) { this.mainActivity = mainActivity; } //设置数据 public void setList(List<MyShoppingBean.DataBean> data){ this.data = data; notifyDataSetChanged(); } //设置商品的加减监听 public void setModifyGoodsItemNumberListener(MainActivity modifyGoodsItemNumberListener) { this.modifyGoodsItemNumberListener = modifyGoodsItemNumberListener; } //商家以及商品是否被选中的一个监听 public void setCheckGroupItemListener(MainActivity checkGroupItemListener) { this.checkGroupItemListener = (CheckGroupItemListener) checkGroupItemListener; } //是否显示删除按钮 public void showDeleteButton(boolean edit){ this.edit = edit; //刷新适配器 notifyDataSetChanged(); } @Override public int getGroupCount() { return data != null ? data.size() : 0; } @Override public int getChildrenCount(int groupPosition) { return data != null && data.get(groupPosition).getList() != null ? data.get(groupPosition).getList().size() : 0; } @Override public Object getGroup(int groupPosition) { return data.get(groupPosition); } @Override public Object getChild(int groupPosition, int childPosition) { return data.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) { if(convertView == null){ convertView = LayoutInflater.from(mainActivity).inflate(R.layout.layout_group,parent,false); } //查找控件 CheckBox ck_group_choosed = convertView.findViewById(R.id.ck_group_choosed); //设置商家checkbox复选框的状态 if(data.get(groupPosition).isGroupChoosed()){ ck_group_choosed.setChecked(true); }else{ ck_group_choosed.setChecked(false); } //ck_group_choosed.setChan ck_group_choosed.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { checkGroupItemListener.checkGroupItem(groupPosition,((CheckBox)view).isChecked()); } }); //赋值 ck_group_choosed.setText(data.get(groupPosition).getSellerName()); return convertView; } @Override public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if(convertView == null){ convertView = LayoutInflater.from(mainActivity).inflate(R.layout.layout_expadapter,parent,false); } //商品选择 CheckBox ck_child_choosed = convertView.findViewById(R.id.ck_child_choose); //商品图片 ImageView iv_show_pic = convertView.findViewById(R.id.iv_show_pic); //商品主标题 TextView tv_commodity_name = convertView.findViewById(R.id.tv_commodity_name); //商品副标题 TextView tv_commodity_attr = convertView.findViewById(R.id.tv_commodity_attr); //商品价格 TextView tv_commodity_price = convertView.findViewById(R.id.tv_commodity_price); //商品数量 TextView tv_commodity_num = convertView.findViewById(R.id.tv_commodity_num); //商品减 TextView iv_sub = convertView.findViewById(R.id.iv_sub); //商品加减中的数量变化 final TextView tv_commodity_show_num = convertView.findViewById(R.id.tv_commodity_show_num); //商品加 TextView iv_add = convertView.findViewById(R.id.iv_add); //删除按钮 Button btn_commodity_delete = convertView.findViewById(R.id.btn_commodity_delete); //设置文本信息 tv_commodity_name.setText(data.get(groupPosition).getList().get(childPosition).getTitle()); tv_commodity_attr.setText(data.get(groupPosition).getList().get(childPosition).getSubhead()); tv_commodity_price.setText(""+data.get(groupPosition).getList().get(childPosition).getPrice()); tv_commodity_num.setText("x"+data.get(groupPosition).getList().get(childPosition).getNum()); tv_commodity_show_num.setText(data.get(groupPosition).getList().get(childPosition).getNum()+""); //分割图片地址 String images = data.get(groupPosition).getList().get(childPosition).getImages(); String[] urls = images.split("\\|"); //加载商品图片 Glide.with(mainActivity) .load(urls[0]) .into(iv_show_pic); //商品加 iv_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { modifyGoodsItemNumberListener.doIncrease(groupPosition,childPosition,tv_commodity_show_num); } }); //设置商品加减的按钮 //商品减 iv_sub.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { modifyGoodsItemNumberListener.doDecrease(groupPosition,childPosition,tv_commodity_show_num); } }); //商品复选框是否被选中 ck_child_choosed.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //isChecked false true checkGroupItemListener.checkChildItem(groupPosition,childPosition,((CheckBox)view).isChecked()); } }); //处理商品的选中状态 if(data.get(groupPosition).getList().get(childPosition).isChildChoosed()){ ck_child_choosed.setChecked(true); }else{ ck_child_choosed.setChecked(false); } //控制删除按钮的隐藏与显示 if(edit){ btn_commodity_delete.setVisibility(View.VISIBLE); }else{ btn_commodity_delete.setVisibility(View.GONE); } return convertView; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return false; } public interface CheckGroupItemListener{ //商家的条目的复选框监听 void checkGroupItem(int groupPosition,boolean isChecked); //商品的 void checkChildItem(int groupPosition,int childPosition,boolean isChecked); } /** * 商品加减接口 */ public interface ModifyGoodsItemNumberListener{ //商品添加操作 void doIncrease(int groupPosition,int childPosition,View view); //商品减少操作 void doDecrease(int groupPosition,int childPosition,View view); } }
转载请注明原文地址: https://www.6miu.com/read-2450007.html

最新回复(0)