Recycleview实现购物车

来源:互联网 发布:淘宝全国销量排行榜 编辑:程序博客网 时间:2024/06/05 07:17


MainActivity.Java的XML布局


 <TextView
        android:id="@+id/f4_header"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@drawable/header"
        android:gravity="center"
        android:text="购物车"
        android:textColor="#fff"
        android:textSize="18sp" />




    <android.support.v7.widget.RecyclerView
        android:id="@+id/recy"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"></android.support.v7.widget.RecyclerView>


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp">




        <TextView
            android:id="@+id/gouwuche_all"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:layout_centerVertical="true"
            android:layout_marginLeft="20dp"
            android:text="全选" />




                <TextView
                    android:id="@+id/textView12"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_marginLeft="150dp"
                    android:layout_toEndOf="@+id/gouwuche_all"
                    android:layout_toRightOf="@+id/gouwuche_all"
                    android:text="合计:" />


                <TextView
                    android:id="@+id/gouwuche_price"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_toRightOf="@+id/textView12"
                    android:text="¥0"
                    android:textColor="#FF6600" />

            <TextView
                android:layout_marginTop="5dp"
                android:layout_marginLeft="140dp"
                android:layout_toEndOf="@+id/gouwuche_all"
                android:layout_toRightOf="@+id/gouwuche_all"
                android:id="@+id/third_totalnum"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="@dimen/padding_10dp"
                android:text="共0件商品"
                android:textSize="@dimen/common_font_size_14"
                android:layout_below="@id/textView12"
                />


        <Button
            android:id="@+id/gouwuche_checkNum"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_marginLeft="180dp"
            android:background="@drawable/header"
            android:text="结算"
            android:textColor="#fff"
            android:textSize="18sp" />


    </RelativeLayout>


布局中有个header.xml,在下面,实现渐变的效果

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"><gradient android:startColor="#FF9000" android:endColor="#FF5000" android:type="linear"/></shape>



Recycleview适配器中的布局gouwuche_item.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="match_parent"
    android:orientation="vertical">


    <LinearLayout
        android:id="@+id/ll_shopcart_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">


        <View
            android:id="@+id/view"
            android:layout_width="match_parent"
            android:layout_height="@dimen/margin_10dp"
            android:background="@color/background_color" />


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical">


            <ImageView
                android:id="@+id/iv_item_shopcart_shopselect"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingBottom="@dimen/margin_10dp"
                android:paddingLeft="@dimen/margin_15dp"
                android:paddingRight="@dimen/margin_15dp"
                android:paddingTop="@dimen/margin_10dp"
                android:src="@drawable/shopcart_selected" />


            <TextView
                android:id="@+id/tv_item_shopcart_shopname"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:drawableLeft="@drawable/shopcart_shop"
                android:drawablePadding="@dimen/padding_5dp"
                android:padding="@dimen/padding_10dp"
                android:text="宝儿家服装"
                android:textColor="@color/cblack" />


        </LinearLayout>


    </LinearLayout>


    <View
        android:layout_width="match_parent"
        android:layout_height="@dimen/margin_1dp"
        android:background="@color/background_color" />


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical">




        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">


            <View
                android:layout_width="match_parent"
                android:layout_height="@dimen/margin_1dp"
                android:background="@color/background_color" />


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">


                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/margin_15dp"
                    android:layout_marginRight="@dimen/margin_15dp"
                    android:src="@drawable/shopcart_selected"
                    android:visibility="invisible" />


                <TextView
                    android:id="@+id/tv_item_shopcart_clothname"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingLeft="@dimen/padding_10dp"
                    android:paddingTop="@dimen/padding_10dp"
                    android:text="穿秋装情侣字母徽章风衣"
                    android:textColor="@color/cblack" />
            </LinearLayout>


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:orientation="horizontal">


                <ImageView
                    android:id="@+id/tv_item_shopcart_clothselect"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="@dimen/margin_15dp"
                    android:src="@drawable/shopcart_selected" />


                <ImageView
                    android:id="@+id/iv_item_shopcart_cloth_pic"
                    android:layout_width="60dp"
                    android:layout_height="60dp"
                    android:layout_margin="@dimen/margin_10dp" />


                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">


                    <TextView
                        android:id="@+id/tv_item_shopcart_cloth_price"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="¥185"
                        android:textColor="@color/main_red_text"
                        android:textSize="@dimen/common_font_size_14" />


                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_vertical">


                        <ImageView
                            android:id="@+id/iv_item_shopcart_cloth_minus"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/shopcart_minus_grey" />


                        <TextView
                            android:id="@+id/et_item_shopcart_cloth_num"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="@dimen/margin_5dp"
                            android:background="@drawable/shopcart_add_btn"
                            android:paddingBottom="@dimen/padding_2dp"
                            android:paddingLeft="@dimen/padding_20dp"
                            android:paddingRight="@dimen/padding_20dp"
                            android:paddingTop="@dimen/padding_2dp"
                            android:text="1"
                            android:textColor="@color/cblack" />


                        <ImageView
                            android:id="@+id/iv_item_shopcart_cloth_add"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="@dimen/margin_5dp"
                            android:src="@drawable/shopcart_add_red" />


                    </LinearLayout>




                </LinearLayout>


                <View
                    android:layout_width="@dimen/margin_1dp"
                    android:layout_height="match_parent"
                    android:layout_marginBottom="@dimen/padding_10dp"
                    android:layout_marginTop="@dimen/padding_10dp"
                    android:background="@color/splitline_color" />


                <ImageView
                    android:id="@+id/iv_item_shopcart_cloth_delete"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="@dimen/margin_20dp"
                    android:src="@drawable/shopcart_delete" />


            </LinearLayout>




        </LinearLayout>

    </LinearLayout>
</LinearLayout>

gouwuche.xml中有两个values下的文件,直接复制就可以了

color.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <color name="result_view">#b0000000</color>    <color name="viewfinder_mask">#60000000</color>    <color name="possible_result_points">#c0ffff00</color></resources>

dimens.xml

<resources>    <dimen name="margin_10dp">10dp</dimen>    <dimen name="padding_5dp">5dp</dimen>    <dimen name="padding_10dp">10dp</dimen>    <dimen name="common_font_size_16">16sp</dimen>    <dimen name="common_font_size_14">14sp</dimen>    <dimen name="height_200dp">200dp</dimen>    <dimen name="margin_30dp">30dp</dimen>    <dimen name="margin_15dp">15dp</dimen>    <dimen name="margin_1dp">1dp</dimen>    <dimen name="margin_5dp">5dp</dimen>    <dimen name="common_font_size_12">12sp</dimen>    <dimen name="padding_2dp">2dp</dimen>    <dimen name="margin_20dp">20dp</dimen></resources>



实现如下效果




适配器类,


package com.bwie.taobao.adapter;


import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.bwie.taobao.R;
import com.bwie.taobao.bean.FindGouWuCheBean;
import com.bwie.taobao.fragment.FragmentFour;
import com.squareup.picasso.Picasso;


import java.util.ArrayList;
import java.util.List;


 


public class ShopRecycleViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context context;
    private List<FindGouWuCheBean.DatasBean.CartListBean.GoodsBean> list;


    public ShopRecycleViewAdapter(Context context) {
        this.context = context;
    }


    public void setData(List<FindGouWuCheBean.DatasBean.CartListBean.GoodsBean> beanlist) {
        if (this.list == null) {
            this.list = new ArrayList<>();
        }
        this.list = beanlist;
        notifyDataSetChanged();
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(context, R.layout.gouwuche_item, null);
        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }


    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final MyViewHolder myViewHolder = (MyViewHolder) holder;
        if (position > 0) {
            if (list.get(position).getStore_id().equals(list.get(position - 1).getStore_id())) {
                myViewHolder.ll_header.setVisibility(View.GONE);
            } else {
                myViewHolder.ll_header.setVisibility(View.VISIBLE);
            }
        } else {
            myViewHolder.ll_header.setVisibility(View.VISIBLE);
        }


        myViewHolder.shopname.setText(list.get(position).getStore_name());
        myViewHolder.childname.setText(list.get(position).getGoods_name());
        myViewHolder.childprice.setText(list.get(position).getGoods_price());
        Picasso.with(context).load(list.get(position).getGoods_image_url()).into(myViewHolder.shoppic);


        //标记商品是否被选中
        if (list.get(position).isSelect()) {
            myViewHolder.checkedselect.setImageDrawable(context.getResources().getDrawable(R.drawable.shopcart_selected));
        } else {
            myViewHolder.checkedselect.setImageDrawable(context.getResources().getDrawable(R.drawable.shopcart_unselected));
        }
        //标记商店是否被选中
        if (list.get(position).isShopSelect()) {
            myViewHolder.shopselect.setImageDrawable(context.getResources().getDrawable(R.drawable.shopcart_selected));
        } else {
            myViewHolder.shopselect.setImageDrawable(context.getResources().getDrawable(R.drawable.shopcart_unselected));
        }


        if (onRefershListener != null) {
            //定义布尔类型
            boolean isSelect = false;
            for (int i = 0; i < list.size(); i++) {
                if (!list.get(i).isSelect()) {
                    //商品不等与true
                    isSelect = false;
                } else {
                    isSelect = true;
                }
            }
            onRefershListener.onRefersh(isSelect, list);
        }
        //删除商品
        myViewHolder.cloth_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onDeleteClickListener != null) {
                    onDeleteClickListener.onDeleteClick(view, position, Integer.valueOf(list.get(position).getGoods_id()));
                }
                list.remove(position);
                FragmentFour.setFirstState(list);
                notifyDataSetChanged();
            }
        });


        //--商品
        myViewHolder.cloth_minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Integer.valueOf(list.get(position).getGoods_num()) > 1) {
                    int count = Integer.valueOf(list.get(position).getGoods_num()) - 1;
                    list.get(position).setGoods_num(count + "");
                    myViewHolder.cloth_num.setText(count + "");
                    notifyDataSetChanged();
                }
            }
        });


        //++商品数量
        myViewHolder.sloth_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String goods_id = list.get(position).getGoods_num();
                int content = Integer.valueOf(goods_id);
                int i = content + 1;
                list.get(position).setGoods_num(i + "");
                myViewHolder.cloth_num.setText(i + "");
                notifyDataSetChanged();
            }
        });




        myViewHolder.checkedselect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                list.get(position).setSelect(!list.get(position).isSelect());
                for (int i = 0; i < list.size(); i++) {
                    for (int j = 0; j < list.size(); j++) {
                        //如果是同一家商铺,并且一种有一个商品是为选中的,全选按钮取消
                        if (list.get(j).getStore_id().equals(list.get(i).getStore_id()) && !list.get(i).isSelect()) {
                            list.get(i).setShopSelect(false);
                            break;
                        } else {
                            list.get(i).setShopSelect(true);
                            break;
                        }
                    }
                }
                notifyDataSetChanged();
            }
        });


        //店铺选中或不选中
        myViewHolder.shopselect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (list.get(position).getIsFirst() == 1) {
                    list.get(position).setShopSelect(!list.get(position).isShopSelect());
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).getStore_id().equals(list.get(position).getStore_id())) {
                            list.get(i).setSelect(list.get(position).isShopSelect());
                        }
                    }
                    notifyDataSetChanged();
                }
            }
        });
    }


    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }


    class MyViewHolder extends RecyclerView.ViewHolder {


        private final ImageView shopselect;
        private final TextView shopname;
        private final TextView childname;
        private final ImageView checkedselect;
        private final ImageView shoppic;
        private final TextView childprice;
        private final ImageView cloth_minus;
        private final TextView cloth_num;
        private final ImageView sloth_add;
        private final ImageView cloth_delete;
        private final LinearLayout ll_header;


        public MyViewHolder(View itemView) {
            super(itemView);
            ll_header = itemView.findViewById(R.id.ll_shopcart_header);
            shopselect = itemView.findViewById(R.id.iv_item_shopcart_shopselect);
            shopname = itemView.findViewById(R.id.tv_item_shopcart_shopname);
            childname = itemView.findViewById(R.id.tv_item_shopcart_clothname);
            checkedselect = itemView.findViewById(R.id.tv_item_shopcart_clothselect);
            shoppic = itemView.findViewById(R.id.iv_item_shopcart_cloth_pic);
            childprice = itemView.findViewById(R.id.tv_item_shopcart_cloth_price);
            cloth_minus = itemView.findViewById(R.id.iv_item_shopcart_cloth_minus);
            cloth_num = itemView.findViewById(R.id.et_item_shopcart_cloth_num);
            sloth_add = itemView.findViewById(R.id.iv_item_shopcart_cloth_add);
            cloth_delete = itemView.findViewById(R.id.iv_item_shopcart_cloth_delete);
        }
    }


    // 商品 选中状态发生变化
    public OnRefershListener onRefershListener;


    public interface OnRefershListener {
        //isSelect true 表示商品全部选中 false 未全部选中
        void onRefersh(boolean isSelect, List<FindGouWuCheBean.DatasBean.CartListBean.GoodsBean> list);
    }


    public void setOnRefershListener(OnRefershListener listener) {
        this.onRefershListener = listener;
    }


    //删除
    public OnDeleteClickListener onDeleteClickListener;


    public interface OnDeleteClickListener {
        void onDeleteClick(View view, int position, int cartid);
    }


    public void setOnDeleteClickListener(OnDeleteClickListener deleteClickListener) {
        this.onDeleteClickListener = deleteClickListener;
    }


    //全选
    public void setUnSelected(int select) {
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                //表示未选中
                if (select == 1) {//商品和商户都不选中
                    list.get(i).setSelect(false);
                    list.get(i).setShopSelect(false);
                } else {
                    list.get(i).setSelect(true);
                    list.get(i).setShopSelect(true);
                }
            }
            notifyDataSetChanged();
        }
    }


}


MainActivity.Java


都在oncreate()方法中

//得到控件

 recy = view.findViewById(R.id.recy);
        all = (TextView) view.findViewById(R.id.gouwuche_all);
        jiesuan = (Button) view.findViewById(R.id.gouwuche_checkNum);
        sumPrice = (TextView) view.findViewById(R.id.gouwuche_price);
        third_totalnum = view.findViewById(R.id.third_totalnum);

//textview设置标识all.setTag(1);//点击textviewall.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View view) {        int select = (Integer) all.getTag();        shopRecycleViewAdapter.setUnSelected(select);        if (select == 1) {            all.setTag(2);        } else {            all.setTag(1);        }    }});
请求数据,可以自己选择




    public void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("key", sp.getString("key", ""));
        OkHttp3Utils.doPost(URLBean.GWC, map, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
            }


            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String string = response.body().string();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject object = new JSONObject(string);
                            if (object.getInt("code") == 200) {
                                if (object.getJSONObject("datas").getJSONArray("cart_list").length() > 0) {
                                    Gson gson = new Gson();
                                    findGouWuCheBean = gson.fromJson(string, FindGouWuCheBean.class);
                                    header.setText("购物车(" + findGouWuCheBean.getDatas().getCart_count() + ")");
                                    //适配数据
                                    shiPei();
                                } else if (object.getJSONObject("datas").getInt("cart_count") == 0) {
                                    // all.setImageResource(R.mipmap.gouwuche_null);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });


            }
        });
    }

适配数据的类



    public void shiPei() {
        goodsBeanList = new ArrayList<>();
        for (int i = 0; i < findGouWuCheBean.getDatas().getCart_list().size(); i++) {
            int length = findGouWuCheBean.getDatas().getCart_list().get(i).getGoods().size();
            for (int j = 0; j < length; j++) {
                goodsBeanList.add(findGouWuCheBean.getDatas().getCart_list().get(i).getGoods().get(j));
            }
        }
        setFirstState(goodsBeanList);
        recy.setLayoutManager(new LinearLayoutManager(getActivity()));
        shopRecycleViewAdapter = new ShopRecycleViewAdapter(getActivity());
        shopRecycleViewAdapter.setData(goodsBeanList);
        recy.setAdapter(shopRecycleViewAdapter);


        //全选按钮
        shopRecycleViewAdapter.setOnRefershListener(new ShopRecycleViewAdapter.OnRefershListener() {
            @Override
            public void onRefersh(boolean isSelect, List<FindGouWuCheBean.DatasBean.CartListBean.GoodsBean> list) {
                if (isSelect == true) {

//R.drawable.shopcart_selected图片下面有
                    Drawable left = getResources().getDrawable(R.drawable.shopcart_selected);
                    all.setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);
                } else {
                    Drawable left = getResources().getDrawable(R.drawable.shopcart_unselected);
                    all.setCompoundDrawablesWithIntrinsicBounds(left, null, null, null);


                }
                //总价
                float numPrice = 0;
                int mTotalNum = 0;


                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).isSelect()) {
                        double price = Double.parseDouble(list.get(i).getGoods_price());
                        double num = Double.parseDouble(list.get(i).getGoods_num());
                        numPrice += price * num;
                        mTotalNum += num;


                    }
                }
                sumPrice.setText(numPrice + "");
                third_totalnum.setText("共" + mTotalNum + "件商品");


            }
        });


        //删除
        shopRecycleViewAdapter.setOnDeleteClickListener(new ShopRecycleViewAdapter.OnDeleteClickListener() {
            @Override
            public void onDeleteClick(View view, int position, int cartid) {
                String url = "http://192.168.23.121/mobile/index.php?act=member_cart&op=cart_del";
                Map<String, String> map = new HashMap<String, String>();
                map.put("key", sp.getString("key", ""));
                map.put("cart_id", goodsBeanList.get(0).getCart_id());
                OkHttp3Utils.doPost(url, map, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }


                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
                            }
                        });


                    }
                });
            }
        });
    }


   //用来标记第一条数据 1显示商户名称,2隐藏商户名称
    public static void setFirstState(List<FindGouWuCheBean.DatasBean.CartListBean.GoodsBean> list) {
        if (list.size() > 0) {
            list.get(0).setIsFirst(1);
            for (int i = 1; i < list.size(); i++) {
                if (list.get(i).getStore_id() == list.get(i - 1).getStore_id()) {
                    list.get(i).setIsFirst(2);
                } else {
                    list.get(i).setIsFirst(1);


                }
            }
        }
    }








原创粉丝点击