Android MVP实现购物车

采用的是MVP方式的购物车

//主布局

  <LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".fragment.Fragment2">

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/qx"
            android:text="全选"
            android:textSize="14sp"
            />
        <android.support.v4.widget.Space
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tvSum"
            android:text="合计"
            android:textSize="24sp"
            android:paddingRight="35dp"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:background="#e70505"
            android:text="结算"
            android:textSize="24sp" />
    </LinearLayout>
</LinearLayout>

//用的是ExpandableListView 会有一个父布局和一个子布局

//父布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

    <CheckBox
        android:id="@+id/checkbox"
        android:focusable="false"
        android:enabled="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tvShopName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24sp"/>
</LinearLayout>

子布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:descendantFocusability="blocksDescendants">

    <CheckBox
        android:id="@+id/cbChecked"
        android:layout_centerVertical="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/ivGoodsIcon"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:padding="10dp"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@id/cbChecked"/>

    <TextView
        android:id="@+id/ivGoodsName"
        android:maxLines="2"
        android:layout_width="270dp"
        android:layout_toRightOf="@id/ivGoodsIcon"
        android:layout_marginLeft="10dp"
        android:textSize="20sp"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/ivGoodsPrice"
        android:layout_toRightOf="@id/ivGoodsIcon"
        android:layout_alignBottom="@id/ivGoodsIcon"
        android:layout_marginLeft="10dp"
        android:layout_width="wrap_content"
        android:textSize="20sp"
        android:layout_height="wrap_content" />

    <com.kq.AddSumLayout
        android:id="@+id/addSubView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:layout_alignBottom="@+id/ivGoodsIcon"/>
</RelativeLayout>

bean类里面需要增加一个boolean的参数用来选中

在这里插入图片描述
在这里插入图片描述

有一个自定义的加减器
//加减器的布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal">

    <TextView
        android:id="@+id/tvSub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="-"
        android:paddingLeft="10dp"
        android:textColor="#8c8a8a"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tvNumber"
        android:gravity="center"
        android:textSize="14sp"
        android:layout_width="80dp"
        android:textColor="#8c8a8a"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tvAdd"
        android:textSize="20sp"
        android:layout_width="wrap_content"
        android:textColor="#8c8a8a"
        android:paddingRight="10dp"
        android:text="+"
        android:layout_height="wrap_content" />
</LinearLayout>

加减器代码

public class AddSumLayout extends LinearLayout {

    private TextView sub,add,number;

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

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

    public AddSumLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
        initListener();
    }
    
	//加,减的点击事件
    private void initListener() {
        add.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                add();
            }
        });
        sub.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                sub();
            }
        });
    }

	//要转换成int类型,判断一下不能少于一
    private void sub() {
        String s = number.getText().toString();
        int parseInt = Integer.parseInt(s);
        if (parseInt>1){
            parseInt--;
            //这是让数量显示的方法
            setCurentCount(parseInt);
        }else {
            Toast.makeText(getContext().getApplicationContext(), "不能在少了", Toast.LENGTH_SHORT).show();
        }

    }

    private void add() {
        String s = number.getText().toString();
        int parseInt = Integer.parseInt(s);
        parseInt++;
        //这是让数量显示的方法
        setCurentCount(parseInt);
    }
	//这是让数量显示的方法
    public void setCurentCount(int num) {
        number.setText(num+"");
        //加减数量后价格计算
        if (onNumChangedListener!=null){
            onNumChangedListener.onNumChanged(this,num);
        }
    }

    private void initView(Context context) {
        View rootview = View.inflate(context, R.layout.layout_add_sum, this);
        sub = (TextView) rootview.findViewById(R.id.tvSub);
        add = (TextView) rootview.findViewById(R.id.tvAdd);
        number = (TextView) rootview.findViewById(R.id.tvNumber);
        number.setText("1");
    }
	//接口回调,用于加减的价格计算
    OnNumChangedListener onNumChangedListener;

    public interface OnNumChangedListener{
        void onNumChanged(View view,int num);
    }

    public void setOnNumChangedListener(OnNumChangedListener onNumChangedListener){
        this.onNumChangedListener=onNumChangedListener;
    }
}

创建一个接口

public interface Shop1 {
    void onSuccess(List<ShopBean.DataBean> list);
    void onFailer(String error);
}

Model层代码

public class ShopModel {

private String path="http://120.27.23.105/product/getCarts?source=android&uid=99";

Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
    }
};

public void shop1(final Shop1 shop1){
        OkHttp okHttp=new OkHttp();
        okHttp.get(path).getDataLiserner(new OkHttp.GetData() {
            @Override
            public void Data(String s) {
                Gson gson=new Gson();
                ShopBean json = gson.fromJson(s, ShopBean.class);
                List<ShopBean.DataBean> data = json.getData();
                shop1.onSuccess(data);
            }
        });
    }
}

View层代码

public interface ShopView {
    void onSuccess(List<ShopBean.DataBean> list);
    void onFailer(String error);
}

Presenter层代码

public class ShopPresenter {
private final ShopModel shopModel;
private ShopView shopView;

    public ShopPresenter(ShopView shopView) {
        this.shopView = shopView;
        shopModel = new ShopModel();
    }

    public void shop1(){
        shopModel.shop1(new Shop1() {
            @Override
            public void onSuccess(List<ShopBean.DataBean> list) {
                shopView.onSuccess(list);
            }

            @Override
            public void onFailer(String error) {
                shopView.onFailer(error);
            }
        });
    }
}

配置适配器

public class ExpandAddapter extends BaseExpandableListAdapter {
private Context mContext;
private List<ShopBean.DataBean> list;
private AddSumLayout.OnNumChangedListener onNumChangedListener;

    public ExpandAddapter(Context mContext, List<ShopBean.DataBean> list) {
        this.mContext = mContext;
        this.list = list;
    }

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

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

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

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return list.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(mContext,R.layout.item_group,null);
             groupViewHolder=new GroupViewHolder();
             groupViewHolder.checkBox=convertView.findViewById(R.id.checkbox);
             groupViewHolder.ShopName=convertView.findViewById(R.id.tvShopName);
             convertView.setTag(groupViewHolder);
        }else {
            groupViewHolder= (GroupViewHolder) convertView.getTag();
        }
        //在bean类里定义的isChecked在这使用
        groupViewHolder.checkBox.setChecked(list.get(groupPosition).isChecked());
        groupViewHolder.ShopName.setText(list.get(groupPosition).getSellerName());
        return convertView;
    }

	//设置子布局
    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ChildViewHolder childViewHolder=null;
        if (convertView==null){
            convertView=View.inflate(mContext,R.layout.item_child,null);
            childViewHolder=new ChildViewHolder();
            childViewHolder.cbChecked = convertView.findViewById(R.id.cbChecked);
            childViewHolder.tvGoodsName = convertView.findViewById(R.id.ivGoodsName);
            childViewHolder.tvGoodsPrice = convertView.findViewById(R.id.ivGoodsPrice);
            childViewHolder.ivGoodsIcon = convertView.findViewById(R.id.ivGoodsIcon);
            childViewHolder.addSubView = convertView.findViewById(R.id.addSubView);
            convertView.setTag(childViewHolder);
        }else {
            childViewHolder= (ChildViewHolder) convertView.getTag();
        }
        childViewHolder.cbChecked.setChecked(list.get(groupPosition).getList().get(childPosition).isChecked());
        childViewHolder.addSubView.setCurentCount(list.get(groupPosition).getList().get(childPosition).getNum());
        childViewHolder.tvGoodsName.setText(list.get(groupPosition).getList().get(childPosition).getTitle());
        childViewHolder.tvGoodsPrice.setText(list.get(groupPosition).getList().get(childPosition).getPrice()+"");
        String images = list.get(groupPosition).getList().get(childPosition).getImages();
        String[] split = images.split("\\|");
        if (split.length>0){
            Picasso.with(mContext).load(split[childPosition]).into(childViewHolder.ivGoodsIcon);
        }
        //加减器的加减之后计算价格
        childViewHolder.addSubView.setOnNumChangedListener(new AddSumLayout.OnNumChangedListener() {
            @Override
            public void onNumChanged(View view, int num) {
            	这里要setNum,而不是getNum,因为要改变集合的数据,价格才能计算
                list.get(groupPosition).getList().get(childPosition).setNum(num);

                if (onNumChangedListener!=null){
                    onNumChangedListener.onNumChanged(view,num);
                }
            }
        });
        return convertView;
    }

    public void setOnNumChangedListener(AddSumLayout.OnNumChangedListener onNumChangedListener){
        this.onNumChangedListener=onNumChangedListener;
    }

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

    class GroupViewHolder{
        CheckBox checkBox;
        TextView ShopName;
    }

    class ChildViewHolder{
        CheckBox cbChecked;

        ImageView ivGoodsIcon;

        TextView tvGoodsName;
        TextView tvGoodsPrice;

        AddSumLayout addSubView;
    }
}

接下来就是使用的代码了

 public class Fragment2 extends Fragment implements ShopView {
    private View view;
    private CheckBox checkBox;
    private TextView tvSum;
    private ExpandableListView expandableListView;
    private ExpandAddapter expandAddapter;

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            final List<ShopBean.DataBean> list = (List<ShopBean.DataBean>) msg.obj;
            //设置设配器
            expandAddapter = new ExpandAddapter(getActivity(),list);
            expandableListView.setAdapter(expandAddapter);
            //循环遍历每一个父类
            for (int i = 0; i < expandAddapter.getGroupCount(); i++) {
            	//打开每一个父类
                expandableListView.expandGroup(i);
            }
            initListener();
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_fragment2, container, false);
        //初始化
        initView();
        return view;
    }

	//初始化
    private void initView() {
        expandableListView = (ExpandableListView) view.findViewById(R.id.expandview);
        checkBox = view.findViewById(R.id.qx);
        tvSum = view.findViewById(R.id.tvSum);
        //调用P层的方法
        ShopPresenter shopPresenter=new ShopPresenter(this);
        shopPresenter.shop1();
        //子类的是否选中
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    setCheckAll(1);
                }else {
                    setCheckAll(0);
                }
            }
        });
    }

	//这是全部选中的方法
    private void setCheckAll(int s) {
        int groupCount = expandAddapter.getGroupCount();
        for (int i = 0; i < groupCount; i++) {
            ShopBean.DataBean group = (ShopBean.DataBean) expandAddapter.getGroup(i);
            List<ShopBean.DataBean.ListBean> list = group.getList();
            for (int j = 0; j < list.size(); j++) {
                ShopBean.DataBean.ListBean listBean = list.get(j);
                listBean.setSelected(s);
            }
        }
        expandAddapter.notifyDataSetChanged();
        //调用计算价钱的方法
        getTotal();
    }

    @Override
    public void onSuccess(List<ShopBean.DataBean> list) {
        Message message = Message.obtain();
        message.obj=list;
        handler.sendMessage(message);

    }
	//这个方法是点击父类,子类全部选中并计算价格
    private void initListener() {
        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                ShopBean.DataBean group = (ShopBean.DataBean) expandAddapter.getGroup(groupPosition);
                group.setChecked(!group.isChecked());
                int c=0;
                if (group.isChecked()){
                    c=1;
                }
                List<ShopBean.DataBean.ListBean> list = group.getList();
                for (int i = 0; i < list.size(); i++) {
                    ShopBean.DataBean.ListBean listBean = list.get(i);
                    listBean.setSelected(c);
                }
                expandAddapter.notifyDataSetChanged();

                //计算总价
                getTotal();
                return true;
            }
        });
        
        //点击子类后计算价格
        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                ShopBean.DataBean.ListBean child = (ShopBean.DataBean.ListBean) expandAddapter.getChild(groupPosition, childPosition);
                boolean checked = child.isChecked();
                if (checked){
                    child.setSelected(0);
                }else {
                    child.setSelected(1);
                }
                expandAddapter.notifyDataSetChanged();
                getTotal();
				//点击加减器后算价格的方法
                expandAddapter.setOnNumChangedListener(new AddSumLayout.OnNumChangedListener() {
                    @Override
                    public void onNumChanged(View view, int num) {
                        getTotal();
                    }
                });
                return true;
            }
        });
    }
	//计算总价的方法
    private void getTotal() {
        double total=0;
        int groupCount = expandAddapter.getGroupCount();
        //分别循环遍历父类和子类是否选中,选中后在计算价格
        for (int i = 0; i < groupCount; i++) {
            ShopBean.DataBean group = (ShopBean.DataBean) expandAddapter.getGroup(i);
            List<ShopBean.DataBean.ListBean> list = group.getList();
            for (int j = 0; j < list.size(); j++) {
                ShopBean.DataBean.ListBean listBean = list.get(j);
                boolean checked = listBean.isChecked();
                if (checked){
                    double price = listBean.getPrice();
                    total+=price*listBean.getNum();
                }
            }
        }
        tvSum.setText("合计:"+total);
    }

    @Override
    public void onFailer(String error) {

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值