我是靠谱客的博主 碧蓝羊,最近开发中收集的这篇文章主要介绍淘宝购物车功能的实现,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

//导入依赖
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.squareup.picasso:picasso:2.5.1'



//主类
public class MainActivity extends AppCompatActivity {    @BindView(R.id.rv)    RecyclerView rv;    @BindView(R.id.checkbox)    CheckBox checkbox;    @BindView(R.id.tv)    TextView tv;    @BindView(R.id.bt)    Button bt;    List<ShopBean.OrderDataBean.CartlistBean> list = new ArrayList<ShopBean.OrderDataBean.CartlistBean>();    private LinearLayoutManager manager;    private ShopAdapter adapter;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        ButterKnife.bind(this);
    //上面可以使用网络请求数据,进行解析
       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++) {                    list.add(shopBean.getOrderData().get(i).getCartlist().get(j));                }            }              //设置线性布局            manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);            rv.setLayoutManager(manager);
             //进行适配 
           adapter = new ShopAdapter(this,list);            rv.setAdapter(adapter);
            adapter.setCheckListener(new ShopAdapter.CheckListener() {                @Override                public void check(boolean check, int position) {                    boolean allCheck = true ;                    float price  = 0 ;                    int count = 0;                    for (int i = 0; i < list.size(); i++) {                        if (list.get(i).isSelect()) {                            price += list.get(i).getPrice() * list.get(i).getCount();                            count++;                        }                    }                    for (int i = 0; i < list.size(); i++) {                        if (!list.get(i).isSelect()) {                            allCheck = false;                            break;                        }                    }                    tv.setText(price+"元");                    bt.setText("结算("+count+")");                    if(allCheck){                        checkbox.setChecked(true);                    }else {                        checkbox.setChecked(false);                    }                }            });        } catch (IOException e) {            e.printStackTrace();        }    }    @OnClick({R.id.checkbox, R.id.bt})    public void onViewClicked(View view) {        switch (view.getId()) {            case R.id.checkbox:                boolean check =   checkbox.isChecked() ;                float price  = 0 ;                int count = 0;                for (int i = 0; i < list.size(); i++) {                    list.get(i).setSelect(check);                    if(check){                        if (list.get(i).isSelect()) {                            price += list.get(i).getPrice() * list.get(i).getCount();                            count++;                        }                    }                }                adapter.notifyDataSetChanged();                tv.setText("¥"+price);                bt.setText("结算("+count+")");                break;            case R.id.bt:                break;        }    }    public  String convertStreamToString(InputStream is) {        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();    }}


// 适配器
public class ShopAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context context;
    private List<ShopBean.OrderDataBean.CartlistBean> list;

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

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.adapter_item, parent, false);
        MyViewHolder viewHolder = new MyViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
     if(holder instanceof  MyViewHolder){
         MyViewHolder myViewHolder = (MyViewHolder) holder;
         myViewHolder.danjia.setText(list.get(position).getPrice()+"");
         Picasso.with(context).load(list.get(position).getDefaultPic()).into(myViewHolder.shopface);
         if(list.get(position).isSelect()){
             if(!myViewHolder.checkbox.isChecked()){
                 myViewHolder.checkbox.setChecked(true);
             }
         } else {
             myViewHolder.checkbox.setChecked(false);
         }

         myViewHolder.checkbox.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {

                 boolean isChecked = list.get(position).isSelect() ;
                 list.get(position).setSelect(!isChecked);
                 notifyDataSetChanged();
                 if(listener != null){
                     listener.check(!isChecked,position);
                 }

             }
         });
         myViewHolder.customviewid.setListener(new MyView.ChangeListener() {
             @Override
             public void onChange(int count) {
                 list.get(position).setCount(count);
                 notifyDataSetChanged();
                 if(listener != null){
                     listener.check(list.get(position).isSelect(),position);
                 }
             }
         });
      }
    }

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

    static class MyViewHolder extends RecyclerView.ViewHolder{
        @BindView(R.id.checkbox)
        CheckBox checkbox;
        @BindView(R.id.shopface)
        ImageView shopface;
        @BindView(R.id.price)
        TextView danjia;
        @BindView(R.id.customviewid)
        MyView customviewid;
        MyViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
    public CheckListener listener;
    public void setCheckListener(CheckListener listener){
        this.listener = listener ;
    }
    interface CheckListener {
        public void check(boolean check,int position);
    }

}
//自定义购物车的加减按钮
public class MyView extends LinearLayout {

    private EditText content;

    public MyView(Context context) {
        super(context);
        init(context);
    }

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }
    private  void init(Context context){
        View view =  LayoutInflater.from(context).inflate(R.layout.view_layout,null);
        addView(view);
        Button revserse = (Button) view.findViewById(R.id.revserse);
        Button add = (Button) view.findViewById(R.id.add);
        content = (EditText) view.findViewById(R.id.content);

        revserse.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String  result =   content.getText().toString().trim() ;
                int integerResult =  Integer.valueOf(result);
                if(integerResult > 1){
                    integerResult = integerResult - 1 ;
                    content.setText(integerResult+"");
                    if(listener != null){
                        listener.onChange(integerResult);
                    }
                }
            }
        });

        add.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String  result =   content.getText().toString().trim() ;
                int integerResult =  Integer.valueOf(result) ;
                integerResult = integerResult + 1 ;
                content.setText(integerResult+"");
                if(listener != null){
                    listener.onChange(integerResult);
                }
            }
        });
        content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                if(listener != null){
                    listener.onChange(Integer.parseInt(s.toString()));
                }
            }
        });
    }
    public ChangeListener listener ;

    public void setListener(ChangeListener listener){
        this.listener = listener;
    }
    interface ChangeListener{
        void onChange(int count);
    }
}
 
//JavaBean可以自己写
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":null,"size":null,"price":20,"count":2},{"id":2,"shopId":1,"shopName":"京东自营","defaultPic":"https://img14.360buyimg.com/n0/jfs/t2971/15/167732091/93002/204c1016/574d9d9aNe4e6fa7a.jpg","productId":2,"productName":null,"color":null,"size":null,"price":148,"count":3}]},{"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":null,"size":null,"price":181,"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":null,"size":null,"price":20,"count":2},{"id":2,"shopId":1,"shopName":"京东自营","defaultPic":"https://img14.360buyimg.com/n0/jfs/t2971/15/167732091/93002/204c1016/574d9d9aNe4e6fa7a.jpg","productId":2,"productName":null,"color":null,"size":null,"price":148,"count":3}]
         */

        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 : null
             * size : null
             * price : 20
             * count : 2
             */

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

            //商品是否被选中
            private boolean isSelect = false;
            //是否是第一个 如果isfirst 等于1 显示商户的名称, 否则隐藏商户的名称
            private int isFirst = 2;
            //商户是否被选中
            private boolean isShopSelect = false;

            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 Object getColor() {
                return color;
            }

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

            public Object getSize() {
                return size;
            }

            public void setSize(Object 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 isSelect() {
                return isSelect;
            }

            public void setSelect(boolean select) {
                isSelect = select;
            }

            public int getIsFirst() {
                return isFirst;
            }

            public void setIsFirst(int isFirst) {
                this.isFirst = isFirst;
            }

            public boolean isShopSelect() {
                return isShopSelect;
            }

            public void setShopSelect(boolean shopSelect) {
                isShopSelect = shopSelect;
            }
        }
    }
}

//布局
//主类布局
<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:id="@+id/rv">

</android.support.v7.widget.RecyclerView>
    <RelativeLayout
        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/checkbox"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:text="全选"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv"
            android:layout_centerInParent="true"
            android:layout_marginLeft="100dp"
            android:text="总价:"
            android:textSize="22sp"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:id="@+id/bt"
            android:text="结算"
            />
    </RelativeLayout>
//自定义View布局
<Button
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:id="@+id/revserse"
    android:text="-"
    android:background="#00FFFFFF"/>
<EditText
    android:text="1"
    android:background="@null"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:gravity="center"
    android:id="@+id/content"/>

<Button
    android:background="#00FFFFFF"
    android:text="+"
    android:id="@+id/add"
    android:layout_width="30dp"
    android:layout_height="30dp"
    />
//适配器里面的条目

<CheckBox
    android:layout_gravity="center"
    android:id="@+id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:orientation="vertical"
    android:layout_gravity="center">

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

        <ImageView
            android:id="@+id/shopface"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:background="@mipmap/ic_launcher" />
        <TextView
            android:id="@+id/price"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="22sp"
            android:layout_gravity="center"/>
    </LinearLayout>
    <com.bwie.gouwuchedemo.MyView
        android:id="@+id/customviewid"
        android:layout_gravity="center"
        android:layout_width="100dp"
        android:layout_height="50dp"/>

</LinearLayout>

json串  shop.json
{  "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
        }
      ]
    }


  ]
}

最后

以上就是碧蓝羊为你收集整理的淘宝购物车功能的实现的全部内容,希望文章能够帮你解决淘宝购物车功能的实现所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部