Android一级购物车简单实现

MainActivity类

package wangyetian.bwie.com.shopcar;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private RecyclerView ry;
    private List<ShopBean.OrderDataBean.CartlistBean> mAllOrderList = new ArrayList<>();
    private RecyclerView mRy;
    private CheckBox mQuan;
    private TextView mZPrice;
    private TextView mZCount;
    private int price=0;
    private int count=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        mRy.setLayoutManager(new LinearLayoutManager(this));
        getData();
        final Adapter adapter = new Adapter(this, mAllOrderList);
        mRy.setAdapter(adapter);

        //监听适配类回调的方法 用于计算总价和总数量 还有给全选赋值
        adapter.setonClickCbListener(new Adapter.onClickCbListener() {
            @Override
            public void onCBListener(boolean flag, List<ShopBean.OrderDataBean.CartlistBean> mList) {
                mAllOrderList  = mList;
                mQuan.setChecked(flag);

                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).isCheck()){
                        price += mList.get(i).getPrice()*mList.get(i).getCount();
                        count += mList.get(i).getCount();
                    }
                }
                mZPrice.setText(price +"");
                mZCount.setText(count +"");
                price =0;
                count =0;
            }
        });

        //全选的点击事件
        mQuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean flag = mQuan.isChecked();
                if (adapter != null){
                    adapter.getCB(flag);
                }
            }
        });


    }

    private void initView() {
        mRy = (RecyclerView) findViewById(R.id.ry);
        mQuan = (CheckBox) findViewById(R.id.quan);
        mZPrice = (TextView) findViewById(R.id.zPrice);
        mZCount = (TextView) findViewById(R.id.zCount);
    }


    public void getData() {
        try {
            //模拟网络请求
            InputStream inputStream = getAssets().open("shop.json");
            String data = convertStreamToString(inputStream);
            Gson gson = new Gson();
            ShopBean shopBean = gson.fromJson(data, ShopBean.class);


            for (int i = 0; i < shopBean.getOrderData().size(); i++) {
                int length = shopBean.getOrderData().get(i).getCartlist().size();
                for (int j = 0; j < length; j++) {
                    mAllOrderList.add(shopBean.getOrderData().get(i).getCartlist().get(j));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String convertStreamToString(InputStream is) {
        /*
          * To convert the InputStream to String we use the BufferedReader.readLine()
          * method. We iterate until the BufferedReader return null which means
          * there's no more data to read. Each line will appended to a StringBuilder
          * and returned as String.
          */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}

自定义控件类

package wangyetian.bwie.com.shopcar;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

/**
 * Created by hp on 2017/11/18.
 */
public class AmountView extends LinearLayout {

    private static final String TAG = "AmountView";
    private int amount = 1; //购买数量

    private OnAmountChangeListener mListener;

    private EditText etAmount;
    private Button btnDecrease;
    private Button btnIncrease;

    public void setEtAmount(int count) {
        etAmount.setText(count +"");
    }

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

    public AmountView(Context context, final AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater.from(context).inflate(R.layout.zdy, this);
        etAmount = (EditText) findViewById(R.id.etAmount);
        btnDecrease = (Button) findViewById(R.id.btnDecrease);
        btnIncrease = (Button) findViewById(R.id.btnIncrease);


        TypedArray obtainStyledAttributes = getContext().obtainStyledAttributes(attrs, R.styleable.AmountView);
        obtainStyledAttributes.recycle();

        //减
        btnDecrease.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                amount = Integer.parseInt(etAmount.getText().toString());
                if (amount > 1) {
                    amount--;
                    etAmount.setText(amount + "");
                }
                //回调到适配类
                mListener.onAmountChange(amount);
            }
        });

        //加
        btnIncrease.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                amount = Integer.parseInt(etAmount.getText().toString());
                amount++;
                etAmount.setText(amount + "");
                mListener.onAmountChange(amount);
            }
        });

    }


    public interface OnAmountChangeListener {
        void onAmountChange(int amount);
    }

    public void setOnAmountChangeListener(OnAmountChangeListener onAmountChangeListener){
        mListener = onAmountChangeListener;
    }

}

适配器

package wangyetian.bwie.com.shopcar;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import java.util.List;

/**
 * Created by hp on 2017/11/18.
 */
public class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<ShopBean.OrderDataBean.CartlistBean> list;
    private Context context;
    private onClickCbListener onClickCbListener;

    public Adapter(Context context, List<ShopBean.OrderDataBean.CartlistBean> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = View.inflate(context,R.layout.ry_item,null);
        ViewHolder1 viewHolder1 = new ViewHolder1(view);
        return viewHolder1;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final ViewHolder1 mHolder = (ViewHolder1) holder;
        mHolder.cb.setChecked(list.get(position).isCheck());
        mHolder.price.setText(list.get(position).getPrice()+"");
        mHolder.zdy.setEtAmount(list.get(position).getCount());

        //多选框点击
        mHolder.cb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //重新给集合赋值
                list.get(position).setCheck(mHolder.cb.isChecked());
                notifyChanged(position);
            }
        });

        //自定义控件
        mHolder.zdy.setOnAmountChangeListener(new AmountView.OnAmountChangeListener() {
            @Override
            public void onAmountChange(int amount) {
                //把变化后的数量重新赋给集合
                list.get(position).setCount(amount);
                notifyChanged(position);
            }
        });

        //删除的点击事件
        mHolder.del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                list.remove(position);
                notifyChanged(position);
            }
        });



    }

    //刷新和回调
    public void notifyChanged(int position){
        boolean flag = true;
        for (int i = 0; i < list.size(); i++) {
            if (!list.get(i).isCheck()){
                flag = false;
                break;
            }
        }
        notifyDataSetChanged();
        onClickCbListener.onCBListener(flag,list);
    }

    //全选的方法
    public void getCB(boolean flag){

        for (int i = 0; i < list.size(); i++) {
            list.get(i).setCheck(flag);
        }
        notifyDataSetChanged();
        onClickCbListener.onCBListener(flag,list);

    }

    interface onClickCbListener{
       void  onCBListener(boolean flag,List<ShopBean.OrderDataBean.CartlistBean> mList);
    }

    public void setonClickCbListener(onClickCbListener onClickCbListener){
        this.onClickCbListener = onClickCbListener;
    }

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

    class ViewHolder1 extends RecyclerView.ViewHolder{
        TextView price;
        CheckBox cb;
        AmountView zdy;
        Button del;
        public ViewHolder1(View itemView) {
            super(itemView);
            price = itemView.findViewById(R.id.price);
            cb = itemView.findViewById(R.id.cb);
            zdy = itemView.findViewById(R.id.zdy);
            del = itemView.findViewById(R.id.del);
        }
    }

}

bean类

package wangyetian.bwie.com.shopcar;

import java.util.List;

/**
 * Created by hp on 2017/11/17.
 */
public class ShopBean {

    /**
     * code : 200
     * orderData : [{"shopId":1,"shopName":"京东自营","cartlist":[{"id":1,"shopId":1,"shopName":"京东自营","defaultPic":"https://img30.360buyimg.com/popWareDetail/jfs/t3208/194/7616404169/244198/369625db/58b7d093N03520fb7.jpg","productId":1,"productName":"三只松鼠_零食大礼包","color":"黑色","size":"18L","price":20,"count":1},{"id":2,"shopId":1,"shopName":"京东自营","defaultPic":"https://img14.360buyimg.com/n0/jfs/t2971/15/167732091/93002/204c1016/574d9d9aNe4e6fa7a.jpg","productId":2,"productName":"小米心跳手环","color":"白色","size":"20XXL","price":148,"count":1}]},{"shopId":2,"shopName":"海澜之家","cartlist":[{"id":1,"shopId":2,"shopName":"海澜之家","defaultPic":"https://img30.360buyimg.com/popWaterMark/jfs/t4075/83/1343091204/132469/9034cb9c/5873496bN68020ba8.jpg","productId":1,"productName":"短袖T恤男 2017夏季新品","color":"蓝色","size":"30X","price":181,"count":1}]},{"shopId":3,"shopName":"OPPO官方旗舰店","cartlist":[{"id":1,"shopId":3,"shopName":"OPPO官方旗舰店","defaultPic":"https://img10.360buyimg.com/cms/jfs/t6064/272/2163314583/157700/442d6477/593c1c49N7c63a7d9.jpg","productId":1,"productName":"OPPO R11 全网通","color":"蓝色","size":"30X","price":1999,"count":1},{"id":2,"shopId":3,"shopName":"OPPO官方旗舰店","defaultPic":"https://img14.360buyimg.com/n0/jfs/t3142/194/4953241722/254855/1651c2b1/585b9021Nf653e48a.jpg","productId":1,"productName":"OPPO R9 全网通","color":"蓝色","size":"30X","price":999,"count":1}]},{"shopId":3,"shopName":"OPPO官方旗舰店","cartlist":[{"id":1,"shopId":3,"shopName":"OPPO官方旗舰店","defaultPic":"https://img10.360buyimg.com/cms/jfs/t6064/272/2163314583/157700/442d6477/593c1c49N7c63a7d9.jpg","productId":1,"productName":"OPPO R11 全网通","color":"蓝色","size":"30X","price":1999,"count":1},{"id":2,"shopId":3,"shopName":"OPPO官方旗舰店","defaultPic":"https://img14.360buyimg.com/n0/jfs/t3142/194/4953241722/254855/1651c2b1/585b9021Nf653e48a.jpg","productId":1,"productName":"OPPO R9 全网通","color":"蓝色","size":"30X","price":999,"count":1}]},{"shopId":3,"shopName":"OPPO官方旗舰店","cartlist":[{"id":1,"shopId":3,"shopName":"OPPO官方旗舰店","defaultPic":"https://img10.360buyimg.com/cms/jfs/t6064/272/2163314583/157700/442d6477/593c1c49N7c63a7d9.jpg","productId":1,"productName":"OPPO R11 全网通","color":"蓝色","size":"30X","price":1999,"count":1},{"id":2,"shopId":3,"shopName":"OPPO官方旗舰店","defaultPic":"https://img14.360buyimg.com/n0/jfs/t3142/194/4953241722/254855/1651c2b1/585b9021Nf653e48a.jpg","productId":1,"productName":"OPPO R9 全网通","color":"蓝色","size":"30X","price":999,"count":1}]},{"shopId":3,"shopName":"OPPO官方旗舰店","cartlist":[{"id":1,"shopId":3,"shopName":"OPPO官方旗舰店","defaultPic":"https://img10.360buyimg.com/cms/jfs/t6064/272/2163314583/157700/442d6477/593c1c49N7c63a7d9.jpg","productId":1,"productName":"OPPO R11 全网通","color":"蓝色","size":"30X","price":1999,"count":1},{"id":2,"shopId":3,"shopName":"OPPO官方旗舰店","defaultPic":"https://img14.360buyimg.com/n0/jfs/t3142/194/4953241722/254855/1651c2b1/585b9021Nf653e48a.jpg","productId":1,"productName":"OPPO R9 全网通","color":"蓝色","size":"30X","price":999,"count":1}]}]
     */

    private int code;
    private List<OrderDataBean> orderData;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public List<OrderDataBean> getOrderData() {
        return orderData;
    }

    public void setOrderData(List<OrderDataBean> orderData) {
        this.orderData = orderData;
    }

    public static class OrderDataBean {
        /**
         * shopId : 1
         * shopName : 京东自营
         * cartlist : [{"id":1,"shopId":1,"shopName":"京东自营","defaultPic":"https://img30.360buyimg.com/popWareDetail/jfs/t3208/194/7616404169/244198/369625db/58b7d093N03520fb7.jpg","productId":1,"productName":"三只松鼠_零食大礼包","color":"黑色","size":"18L","price":20,"count":1},{"id":2,"shopId":1,"shopName":"京东自营","defaultPic":"https://img14.360buyimg.com/n0/jfs/t2971/15/167732091/93002/204c1016/574d9d9aNe4e6fa7a.jpg","productId":2,"productName":"小米心跳手环","color":"白色","size":"20XXL","price":148,"count":1}]
         */

        private int shopId;
        private String shopName;
        private List<CartlistBean> cartlist;

        public int getShopId() {
            return shopId;
        }

        public void setShopId(int shopId) {
            this.shopId = shopId;
        }

        public String getShopName() {
            return shopName;
        }

        public void setShopName(String shopName) {
            this.shopName = shopName;
        }

        public List<CartlistBean> getCartlist() {
            return cartlist;
        }

        public void setCartlist(List<CartlistBean> cartlist) {
            this.cartlist = cartlist;
        }

        public static class CartlistBean {
            /**
             * id : 1
             * shopId : 1
             * shopName : 京东自营
             * defaultPic : https://img30.360buyimg.com/popWareDetail/jfs/t3208/194/7616404169/244198/369625db/58b7d093N03520fb7.jpg
             * productId : 1
             * productName : 三只松鼠_零食大礼包
             * color : 黑色
             * size : 18L
             * price : 20
             * count : 1
             */

            private int id;
            private int shopId;
            private String shopName;
            private String defaultPic;
            private int productId;
            private String productName;
            private String color;
            private String size;
            private int price;
            private int count;
            private boolean check;

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public int getShopId() {
                return shopId;
            }

            public void setShopId(int shopId) {
                this.shopId = shopId;
            }

            public String getShopName() {
                return shopName;
            }

            public void setShopName(String shopName) {
                this.shopName = shopName;
            }

            public String getDefaultPic() {
                return defaultPic;
            }

            public void setDefaultPic(String defaultPic) {
                this.defaultPic = defaultPic;
            }

            public int getProductId() {
                return productId;
            }

            public void setProductId(int productId) {
                this.productId = productId;
            }

            public String getProductName() {
                return productName;
            }

            public void setProductName(String productName) {
                this.productName = productName;
            }

            public String getColor() {
                return color;
            }

            public void setColor(String color) {
                this.color = color;
            }

            public String getSize() {
                return size;
            }

            public void setSize(String size) {
                this.size = size;
            }

            public int getPrice() {
                return price;
            }

            public void setPrice(int price) {
                this.price = price;
            }

            public int getCount() {
                return count;
            }

            public void setCount(int count) {
                this.count = count;
            }

            public boolean isCheck() {
                return check;
            }

            public void setCheck(boolean check) {
                this.check = check;
            }
        }
    }
}

MainActivity布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="wangyetian.bwie.com.shopcar.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/ry"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">
        <CheckBox
            android:id="@+id/quan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/zPrice"
            android:layout_width="100dp"
            android:layout_height="50dp" />
        <TextView
            android:id="@+id/zCount"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

</LinearLayout>

自定义控件布局

<?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="horizontal">

    <Button
        android:id="@+id/btnDecrease"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#f00"
        android:gravity="center"
        android:text="-" />

    <EditText
        android:id="@+id/etAmount"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:background="@null"
        android:gravity="center"
        android:inputType="number"
        android:minWidth="60dp"
        android:text="1" />

    <Button
        android:id="@+id/btnIncrease"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#f0f"
        android:gravity="center"
        android:text="+" />
</LinearLayout>

底部布局

<?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="100dp"
    android:orientation="horizontal">

    <CheckBox
        android:id="@+id/cb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"/>
    <TextView
        android:id="@+id/price"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:gravity="center"/>
    <wangyetian.bwie.com.shopcar.AmountView
        android:id="@+id/zdy"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        />
    <Button
        android:id="@+id/del"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="删除"/>

</LinearLayout>

attrs文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="AmountView">
        <!-- 左右2边+-按钮的宽度 -->
        <attr name="btnWidth" format="dimension" />
        <!-- 中间TextView的宽度 -->
        <attr name="tvWidth" format="dimension" />
        <!--<attr name="tvColor" format="color"/>-->
        <attr name="tvTextSize" format="dimension"/>
        <attr name="btnTextSize" format="dimension"/>
    </declare-styleable>
</resources>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值