购物车一级列表

MainActivity

public class MainActivity extends Activity {
    RecyclerView rv;
    LinearLayout linearlayout;
    TextView tv_main, third_totalprice, third_totalnum, third_submit;
    private ShopAdapter adapter;
    private LinearLayoutManager manager;
    private List<ShopBean.OrderDataBean.CartlistBean> mAllorderList = new ArrayList<>();

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

        tv_main = findViewById(R.id.tv_main);
        third_totalprice = findViewById(R.id.third_totalprice);
        third_totalnum = findViewById(R.id.third_totalnum);
        third_submit = findViewById(R.id.third_submit);
        linearlayout = findViewById(R.id.linearlayout);
        rv = findViewById(R.id.rv);
        //模拟网络请求
        getData();
        //全选
        // 1 为选中  2 选中
        tv_main.setTag(1);

        manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);

        adapter = new ShopAdapter(this);

        rv.setLayoutManager(manager);
        rv.setAdapter(adapter);

        adapter.add(mAllorderList);
        adapter.setCheckBoxListener(new ShopAdapter.CheckBoxListener() {

            @Override
            public void check(int position, int count, boolean check, List<ShopBean.OrderDataBean.CartlistBean> list) {
                sum(list);
            }
        });



        adapter.setCustomViewListener(new ShopAdapter.CustomViewListener() {
            @Override
            public void click(int count,List<ShopBean.OrderDataBean.CartlistBean> list) {
                sum(list);
            }
        });

        adapter.setDelListener(new ShopAdapter.DelListener() {
            @Override
            public void del(int position,List<ShopBean.OrderDataBean.CartlistBean> list) {
                sum(list);
            }
        });

    }

    float price = 0;
    int count;

    /**
     * 计算总价
     *
     * @param mAllOrderList
     */
    private void sum(List<ShopBean.OrderDataBean.CartlistBean> mAllOrderList) {
        price = 0;
        count = 0;

        boolean allCheck = true;
        for (ShopBean.OrderDataBean.CartlistBean bean : mAllOrderList) {
            if (bean.isChock()) {
                //得到总价
                price += bean.getPrice() * bean.getCount();
                //得到商品个数
                count += bean.getCount();
            } else {
                // 只要有一个商品未选中,全选按钮 应该设置成 为选中
                allCheck = false;
            }
        }

        third_totalprice.setText("总价: " + price);
        third_totalnum.setText("共" + count + "件商品");

        if (allCheck) {
            tv_main.setTag(2);
            tv_main.setBackgroundResource(R.drawable.shopcart_selected);
        } else {
            tv_main.setTag(1);
            tv_main.setBackgroundResource(R.drawable.shopcart_unselected);
        }

    }

    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) {
        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();
    }

    boolean select = false;

    @OnClick(R.id.tv_main)
    public void onClick() {
        //全选按钮 点击事件
        int tag = (Integer) tv_main.getTag();
        if (tag == 1) {
            tv_main.setTag(2);
            select = true;
        } else {
            tv_main.setTag(1);
            select = false;
        }
        for (ShopBean.OrderDataBean.CartlistBean bean : mAllorderList) {
            bean.setChock(select);
        }
        adapter.notifyDataSetChanged();

        sum(adapter.getList());


    }

}
 
主Activtiy布局
<?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:orientation="vertical"
    android:layout_height="match_parent"
    tools:context="com.zhangyongbo.gouwuche.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        />
      <LinearLayout
          android:id="@+id/linearlayout"
          android:layout_weight="0"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="horizontal"
          android:gravity="center_vertical"
          >
       <TextView
           android:id="@+id/tv_main"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginLeft="@dimen/margin_10dp"
           android:drawableLeft="@drawable/shopcart_unselected"
           android:text="全选"
           android:drawablePadding="@dimen/padding_5dp"
           />


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

              <TextView
                  android:id="@+id/third_totalprice"
                  android:layout_width="200dp"
                  android:layout_height="wrap_content"
                  android:paddingLeft="@dimen/padding_10dp"
                  android:paddingTop="@dimen/padding_10dp"
                  android:text="总价:"
                  android:textColor="#000000"
                  android:textSize="@dimen/common_font_size_16"
                  />

              <TextView
                  android:textColor="#000000"
                  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:paddingBottom="@dimen/padding_10dp"
                  />

          </LinearLayout>

          <TextView
              android:id="@+id/third_submit"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="去结算"
              android:paddingLeft="@dimen/margin_30dp"
              android:paddingRight="@dimen/margin_30dp"
              android:paddingTop="@dimen/padding_10dp"
              android:paddingBottom="@dimen/padding_10dp"
              android:textColor="#000000"
              android:layout_marginRight="@dimen/margin_10dp"
              />

      </LinearLayout>

</LinearLayout>

 
自定义View
 
public class CustomView extends LinearLayout {
    private EditText editText;
    private Button revserse;
    private Button add;
    private int mCount = 1 ;
    public CustomView(Context context) {
        super(context);
    }
    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
       View view =   LayoutInflater.from(context).inflate(R.layout.customview,null,false);
        revserse = (Button) view.findViewById(R.id.revserse);
        add = (Button) view.findViewById(R.id.add);
        editText = (EditText) view.findViewById(R.id.content);
        revserse.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //减号
                try {
                    String content =  editText.getText().toString().trim() ;
                    int count =  Integer.valueOf(content)-1;
                    mCount = count;
                    if(count >=1){

                        editText.setText(count+"");
                    }

                    if(listener != null){
                        listener.click(count);
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }


            }
        });
        add.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //加号
                try {
                    String content =  editText.getText().toString().trim() ;
                    int count =  Integer.valueOf(content)+1;
                    mCount = count;

                    editText.setText(count+"");
                    if(listener != null){
                        listener.click(count);
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        });
        addView(view);
    }
     public void setEditText(int count){
         editText.setText(count+"");
     }

    public int getCurrentCount(){

        return mCount ;
    }

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    public ClickListener listener;

    public void setListener(ClickListener listener){
        this.listener = listener;
    }

    public interface ClickListener {
        public void click(int count);
    }

}

自定义View布局xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="10dp"
        android:layout_height="wrap_content"
        android:id="@+id/revserse"
        android:text="-"
        android:background="#00FFFFFF"/>
    <EditText
        android:text="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/content"/>
    <Button
        android:background="#00FFFFFF"
        android:text="+"
        android:id="@+id/add"
        android:layout_width="10dp"
        android:layout_height="wrap_content"
        />
</LinearLayout>

 
适配器
 
public class ShopAdapter extends RecyclerView.Adapter<ShopAdapter.IViewHolder> {
    private Context context;
    private List<ShopBean.OrderDataBean.CartlistBean> list ;
    public ShopAdapter(Context context) {
        this.context = context;
    }


    /**
     * 更新数据
     * @param list
     */
    public void add(List<ShopBean.OrderDataBean.CartlistBean> list){
        if(this.list == null){
            this.list = new ArrayList<>();
        }
        this.list.addAll(list);
        notifyDataSetChanged();
    }

    @Override
    public ShopAdapter.IViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(context, R.layout.shop_apdata, null);
        return new IViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ShopAdapter.IViewHolder holder, final int position) {



        //防止checkbox 滑动 错乱
        holder.checkbox.setChecked(list.get(position).isChock());

        holder.danjia.setText(list.get(position).getPrice()+"");

        ImageLoader.getInstance().displayImage(list.get(position).getDefaultPic(),holder.shopface);


        /**
         * checkbox 点击事件
         */
        holder.checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                list.get(position).setChock(holder.checkbox.isChecked());
                notifyDataSetChanged();

                if(checkBoxListener != null){
                    checkBoxListener.check(position,holder.customviewid.getCurrentCount(),holder.checkbox.isChecked(),list);
                }
            }
        });


        /**
         * 加减监听
         */
        holder.customviewid.setListener(new CustomView.ClickListener() {
            @Override
            public void click(int count) {


                //更新数据源
                list.get(position).setCount(count);
                notifyDataSetChanged();

                if(listener != null){
                    listener.click(count,list);
                }


            }
        });

        /**
         * 删除点击事件
         */
        holder.del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                list.remove(position);
                notifyDataSetChanged();

                if(delListener != null){
                    delListener.del(position,list);
                }


            }
        });




    }

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

    static class IViewHolder extends RecyclerView.ViewHolder {
        CheckBox checkbox;
        ImageView shopface;
        TextView danjia;
        CustomView customviewid;
        Button del ;

        IViewHolder(View view) {

            super(view);
            checkbox = view.findViewById(R.id.checked_shop);
            shopface = view.findViewById(R.id.shopface);
            danjia = view.findViewById(R.id.danjia);
            customviewid = view.findViewById(R.id.customviewid);
            del = view.findViewById(R.id.shop_btn_del);
        }
    }



    public List<ShopBean.OrderDataBean.CartlistBean> getList(){
        return list;
    }

    CheckBoxListener checkBoxListener;

    /**
     * checkbox 点击事件
     * @param listener
     */
    public void setCheckBoxListener(CheckBoxListener listener){
        this.checkBoxListener = listener;
    }
    interface CheckBoxListener {
        public void check(int position,int count, boolean check,List<ShopBean.OrderDataBean.CartlistBean> list);
    }




    CustomViewListener listener;

    /**
     * 加减号 点击事件
     * @param listener
     */
    public void setCustomViewListener(CustomViewListener listener){
        this.listener = listener;
    }
    interface CustomViewListener {
        public void click(int count,List<ShopBean.OrderDataBean.CartlistBean> list);
    }



    DelListener delListener ;
    /**
     * 加减号 删除按钮事件
     * @param listener
     */
    public void setDelListener(DelListener listener) {
        this.delListener = listener ;
    }
    interface DelListener {
        public void del(int position,List<ShopBean.OrderDataBean.CartlistBean> list);
    }

}

子布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">


    <CheckBox
        android:layout_gravity="center"
        android:id="@+id/checked_shop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


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


        <ImageView
            android:id="@+id/shopface"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:src="@mipmap/ic_launcher"/>

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


            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/danjia"/>

            <com.zhangyongbo.gouwuche.CustomView
                android:id="@+id/customviewid"
                android:layout_width="100dp"
                android:layout_height="50dp"/>

        </LinearLayout>


        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/shop_btn_del"
            android:text="删除"/>


    </LinearLayout>
</LinearLayout>

ImageLoade的文件
public class MyApps extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        File file = new File(Environment.getExternalStorageDirectory().getPath()+"Images0718");
        ImageLoaderConfiguration conn = new ImageLoaderConfiguration.Builder(this)
                .threadPoolSize(5)
                .memoryCacheExtraOptions(80, 80)
                .memoryCacheSize(2 * 1024 * 1024)
                .threadPriority(1000)
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .diskCacheSize(50 * 1024 * 1024)
                .build();
        ImageLoader.getInstance().init(conn);
    }
}

这里一级列表不是网络请求数据,这里用到的是假数据
下面是bean包
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}]}]
     */

    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 chock;

            public boolean isChock() {
                return chock;
            }

            public void setChock(boolean chock) {
                this.chock = chock;
            }

            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;
            }



        }
    }
}

这里还需要一个json数据,选中你的项目右击点击NeW然后选择Folder
就ok然后不Json文件粘进assets里就ok。
下面事需要的依赖
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
compile files('libs/universal-image-loader-1.9.3-with-sources.jar')
compile files('libs/gson-2.2.4.jar')
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
compile 'com.jakewharton:butterknife:7.0.1'
架包需要一个
Gson和ImageLoagade的就好,清单文件需要一个联网全选,ImageLoage
需要在清单文件注册.
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值