简单的购物车 RecyclerView嵌套

具体代码:https://github.com/sunli0828/Month_Demo/tree/master/sunli1218

购物车接口:
public static final String URL_SHOPCAR_INFO = “****************************”;

购物车主页面

public class MainActivity extends AppCompatActivity implements IView, View.OnClickListener {

    private IPresenterImpl iPresenter;
    private RecyclerView main_recycler_car;
    private CheckBox main_ck_all;
    private TextView main_text_totalPrice;
    private Button main_btn_totalNum;
    private List<CarBean.DataBean> carBeanData;
    private SellerAdapter sellerAdapter;
    private Button main_btn_linkage;

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

        iPresenter = new IPresenterImpl(this);

        iPresenter.startRequest(ApiUtils.URL_SHOPCAR_INFO, null, CarBean.class);

        initView();
    }
	//加载视图
    private void initView() {
        main_recycler_car = findViewById(R.id.main_recycler_car);
        main_ck_all = findViewById(R.id.main_ck_all);
        main_text_totalPrice = findViewById(R.id.main_text_totalPrice);
        main_btn_totalNum = findViewById(R.id.main_btn_totalNum);
        main_btn_linkage = findViewById(R.id.main_btn_linkage);

        main_ck_all.setOnClickListener(this);
        main_btn_totalNum.setOnClickListener(this);
        main_btn_linkage.setOnClickListener(this);
	//第一层商家的适配器
        sellerAdapter = new SellerAdapter(this);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        main_recycler_car.setLayoutManager(linearLayoutManager);
        main_recycler_car.setAdapter(sellerAdapter);

        sellerAdapter.setListener(new SellerAdapter.CarCallBackListener() {
            @Override
            public void callBack(List<CarBean.DataBean> list) {
                double totalPrice = 0;
                int num = 0, totalNum = 0;
                for (int a = 0; a < list.size(); a++) {
                    List<CarBean.DataBean.ListBean> listSellerThings = list.get(a).getList();
                    for (int i = 0; i < listSellerThings.size(); i++) {
                        totalNum += listSellerThings.get(i).getNum();
                        if (listSellerThings.get(i).isCheck()) {
                            totalPrice += listSellerThings.get(i).getPrice() * listSellerThings.get(i).getNum();
                            num += listSellerThings.get(i).getNum();
                        }
                    }
                }

                if (num < totalNum) {
                    main_ck_all.setChecked(false);
                } else {
                    main_ck_all.setChecked(true);
                }

                main_text_totalPrice.setText("合计: ¥" + totalPrice);
                main_btn_totalNum.setText("付款(" + num + ")");
            }
        });
    }
	//按钮点击事件的方法
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        //全选
            case R.id.main_ck_all:
                boolean checked = main_ck_all.isChecked();
                checkSeller(checked);
                break;
                //总数
            case R.id.main_btn_totalNum:
                Intent intentMap = new Intent(MainActivity.this, MapActivity.class);
                startActivity(intentMap);
                break;
                //这是二级联动
            case R.id.main_btn_linkage:
                Intent intentLevel = new Intent(MainActivity.this, LevelLinkActivity.class);
                startActivity(intentLevel);
                break;
            default:
                break;
        }
    }

    private void checkSeller(boolean bool) {

        double totalPrice = 0;
        int num = 0;

        for (int a = 0; a < carBeanData.size(); a++) {
            CarBean.DataBean dataBean = carBeanData.get(a);
            dataBean.setCheck(bool);

            List<CarBean.DataBean.ListBean> listSellerThings = carBeanData.get(a).getList();

            for (int i = 0; i < listSellerThings.size(); i++) {
                listSellerThings.get(i).setCheck(bool);
                totalPrice = totalPrice + (listSellerThings.get(i).getPrice() * listSellerThings.get(i).getNum());
                num = num + listSellerThings.get(i).getNum();
            }
        }

        if (bool) {
            main_text_totalPrice.setText("合计: " + totalPrice);
            main_btn_totalNum.setText("付款(" + num + ")");
        } else {
            main_text_totalPrice.setText("合计: 0.00");
            main_btn_totalNum.setText("付款(0)");
        }
        sellerAdapter.notifyDataSetChanged();
    }
	//mvp请求数据成功回调方法
    @Override
    public void showResponseData(Object data) {
        if (data instanceof CarBean) {
            CarBean carBean = (CarBean) data;

            carBeanData = carBean.getData();
            if (carBeanData != null) {
                carBeanData.remove(0);
                sellerAdapter.setList(carBeanData);
            }
        }
    }

    @Override
    public void showResponseFail(Exception e) {}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        iPresenter.onDetach();
    }
}

第一层 商家的名字的适配器

public class SellerAdapter extends RecyclerView.Adapter<SellerAdapter.SellerViewHolder> {

    private List<CarBean.DataBean> dataBeanList = new ArrayList<>();
    private Context dataContext;

    public SellerAdapter(Context dataContext) {
        this.dataContext = dataContext;
    }
	//创建视图
    @NonNull
    @Override
    public SellerViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = View.inflate(dataContext, R.layout.adapter_item_seller, null);
        SellerViewHolder sellerViewHolder = new SellerViewHolder(view);
        return sellerViewHolder;
    }
	//绑定视图
    @Override
    public void onBindViewHolder(@NonNull final SellerViewHolder sellViewHolder, final int i) {
        sellViewHolder.seller_name.setText(dataBeanList.get(i).getSellerName());

//商家商品内容的适配器
        final SellerThingsAdapter sellerThingsAdapter = new SellerThingsAdapter(dataBeanList.get(i).getList(), dataContext);
        //线性管理
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(dataContext);
        sellViewHolder.seller_recycler.setLayoutManager(linearLayoutManager);
        //设置适配器
        sellViewHolder.seller_recycler.setAdapter(sellerThingsAdapter);

        sellViewHolder.seller_check.setChecked(dataBeanList.get(i).isCheck());

        sellerThingsAdapter.setListener(new SellerThingsAdapter.CarCallBackListener() {
            @Override
            public void callBack() {
                if (carCallBackListener != null) {
                    carCallBackListener.callBack(dataBeanList);
                }

                List<CarBean.DataBean.ListBean> listBeans = dataBeanList.get(i).getList();
                boolean isAllChecked = true;
                for (CarBean.DataBean.ListBean bean : listBeans) {
                    if (!bean.isCheck()) {
                        isAllChecked = false;
                        break;
                    }
                }

                sellViewHolder.seller_check.setChecked(isAllChecked);
                dataBeanList.get(i).setCheck(isAllChecked);
            }
        });

        sellViewHolder.seller_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataBeanList.get(i).setCheck(sellViewHolder.seller_check.isChecked());
                sellerThingsAdapter.selectOrRemoveAll(sellViewHolder.seller_check.isChecked());
            }
        });
    }

    @Override
    public int getItemCount() {
        return dataBeanList.size();
    }
	//内部类
    public class SellerViewHolder extends RecyclerView.ViewHolder {
        RecyclerView seller_recycler;
        TextView seller_name;
        CheckBox seller_check;
        public SellerViewHolder(@NonNull View itemView) {
            super(itemView);
            seller_recycler = itemView.findViewById(R.id.seller_recycler);
            seller_name = itemView.findViewById(R.id.item_text_sellerName);
            seller_check = itemView.findViewById(R.id.checked_seller);
        }
    }

    public void setList(List<CarBean.DataBean> list) {
        this.dataBeanList = list;
        notifyDataSetChanged();
    }
	//接口回调
    private CarCallBackListener carCallBackListener;

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

    public interface CarCallBackListener {
        void callBack(List<CarBean.DataBean> list);
    }
}

//商品的适配器

public class SellerThingsAdapter extends RecyclerView.Adapter<SellerThingsAdapter.SellerTingsViewHolder> {

    private List<CarBean.DataBean.ListBean> listBeanList = new ArrayList<>();
    private Context listBeanContext;

    public SellerThingsAdapter(List<CarBean.DataBean.ListBean> listBeanList, Context listBeanContext) {
        this.listBeanList = listBeanList;
        this.listBeanContext = listBeanContext;
    }

    @NonNull
    @Override
    public SellerTingsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = View.inflate(listBeanContext, R.layout.adapter_item_seller_things, null);
        SellerTingsViewHolder sellerTingsViewHolder = new SellerTingsViewHolder(view);
        return sellerTingsViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final SellerTingsViewHolder sellerTingsViewHolder, final int i) {
        String url = listBeanList.get(i).getImages().split("\\|")[0].replace("https", "http");
        Glide.with(listBeanContext).load(url).into(sellerTingsViewHolder.sellerthings_icon);
        sellerTingsViewHolder.sellerthings_title.setText(listBeanList.get(i).getTitle());
        sellerTingsViewHolder.sellerthings_price.setText(listBeanList.get(i).getPrice() + "");

        sellerTingsViewHolder.sellerthings_ckAll.setChecked(listBeanList.get(i).isCheck());

        sellerTingsViewHolder.sellerthings_ckAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                listBeanList.get(i).setCheck(isChecked);
                if (carCallBackListener != null) {
                    carCallBackListener.callBack();
                }
            }
        });
    }

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

    public class SellerTingsViewHolder extends RecyclerView.ViewHolder{
        CheckBox sellerthings_ckAll;
        ImageView sellerthings_icon;
        TextView sellerthings_title;
        TextView sellerthings_price;
        public SellerTingsViewHolder(@NonNull View itemView) {
            super(itemView);
            sellerthings_ckAll = itemView.findViewById(R.id.item_things_check_product);
            sellerthings_icon = itemView.findViewById(R.id.item_things_icon_product);
            sellerthings_title = itemView.findViewById(R.id.item_things_text_product_title);
            sellerthings_price = itemView.findViewById(R.id.item_things_text_product_price);
        }
    }

    public void selectOrRemoveAll(boolean isSelectedAll) {
        for (CarBean.DataBean.ListBean listBean : listBeanList) {
            listBean.setCheck(isSelectedAll);
        }
        notifyDataSetChanged();
    }

    private CarCallBackListener carCallBackListener;

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

    public interface CarCallBackListener {
        void callBack();
    }
}

自定义View做加减

//xml文件
① activity_main.xml

<?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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.5"
        >
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="购物车"
            android:background="@color/colorPrimary"
            android:gravity="center"
            android:textColor="#fff"
            />
    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="8.5"
        android:id="@+id/main_recycler_car"
        ></android.support.v7.widget.RecyclerView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"
        >
        <CheckBox
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            android:id="@+id/main_ck_all"
            android:layout_marginLeft="10dp"
            />
        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:text="共计: ¥0.00"
            android:gravity="center_vertical"
            android:id="@+id/main_text_totalPrice"
            />
        <Button
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@android:color/holo_red_light"
            android:text="付款(0)"
            android:textColor="#fff"
            android:id="@+id/main_btn_totalNum"
            />
        <Button
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="二级联动"
            android:background="@android:color/holo_red_light"
            android:textColor="#fff"
            android:layout_marginLeft="5dp"
            android:id="@+id/main_btn_linkage"
            />
    </LinearLayout>

</LinearLayout>

② adapter_item_seller.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:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <CheckBox
            android:id="@+id/checked_seller"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="20dp" />

        <TextView
            android:id="@+id/item_text_sellerName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            />
    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginTop="10dp"
        android:id="@+id/seller_recycler"
        ></android.support.v7.widget.RecyclerView>

</LinearLayout>

③ adapter_item_seller_things

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:background="#ffffff">

    <CheckBox
        android:id="@+id/item_things_check_product"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp" />

    <ImageView
        android:id="@+id/item_things_icon_product"
        android:layout_width="100dp"
        android:layout_height="80dp"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="10dp"
        android:layout_toRightOf="@+id/item_things_check_product" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/item_things_icon_product">

        <TextView
            android:id="@+id/item_things_text_product_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:lines="2"
            android:textColor="#222222"
            android:textSize="14sp" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_alignParentBottom="true">

            <TextView
                android:id="@+id/item_things_text_product_price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:textColor="@color/colorPrimary"
                android:textSize="12sp"
                android:layout_marginRight="20dp"/>

            <!--<com.sunli.sunli1218.CustomCounterView
                android:id="@+id/custom_things_counter"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/item_things_text_product_price" />-->
        </RelativeLayout>
    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:layout_alignParentBottom="true"
        android:background="#cccccc"
        android:layout_marginTop="10dp"
        />
</RelativeLayout>

④ 自定义view

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/reduce_counts"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_centerVertical="true"
        android:src="@mipmap/jian" />

    <ImageView
        android:id="@+id/add_counts"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/edit_shop_counts"
        android:src="@mipmap/add" />

    <EditText
        android:id="@+id/edit_shop_counts"
        android:layout_width="50dp"
        android:layout_height="45dp"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/reduce_counts"
        android:gravity="center_horizontal"
        android:inputType="number"
        android:text="1"
        android:textSize="16sp" />
</RelativeLayout>

这就是大概的效果了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
联动 RecyclerView:即使不用饿了么订餐,也请务必收藏好该库!由来Linkage-RecyclerView 是一款基于 MVP 架构开发的二级联动列表控件。它是因 “RxJava 魔法师” 这个项目的需求而存在。在最初寻遍了 GitHub 也没有找到合适的开源库(高度解耦、可远程依赖)之后,我决心研究参考现有开源项目关于二级联动的逻辑,并自己动手编写一个 高度解耦、轻松配置、可通过 maven 仓库远程依赖 的真正的第三方库。Linkage-RecyclerView 的个性化配置十分简单,依托于 MVP 的 “配置解耦” 特性,使用者无需知道内部的实现细节,仅通过实现 Config 类即可完成功能的定制和扩展。此外,在不设置自定义配置的情况下,LinkageRecyclerView 最少只需 一行代码即可运行起来。RxMagicEleme LinearEleme Grid目标Linkage-RecyclerView 的目标是:一行代码即可接入二级联动列表。除了一键接入而省去 99% 不必要的、复杂的、重复的工作外,你还可以从这个开源项目获得的内容包括:整洁的代码风格和标准的资源命名规范。MVP 架构在第三库中的最佳实践:使用者无需了解内部逻辑,通过实现接口即可轻松完成个性化配置。优秀的代码分层和封装思想,在不做任何个性化配置的情况下,一行代码即可接入。主体工程基于前沿的、遵循关注点分离的 JetPack MVVM 架构。AndroidX 和 Material Design 2 的全面使用。ConstraintLayout 约束布局的最佳实践。绝不使用 Dagger,绝不使用奇技淫巧、编写艰深晦涩的代码。如果你正在思考 如何为项目挑选合适的架构 的话,这个项目值得你参考!简单使用:1.在 build.gradle 中添加对该库的依赖。implementation 'com.kunminx.linkage:linkage-recyclerview:1.2.0'2.依据默认的联动实体类(DefaultLinkageItem)的结构准备一串 JSON。// DefaultLinkageItem.ItemInfo 包含三个字段: String title //二级选项的标题(必填) String group //二级选项所在分组的名称,要和对应的一级选项的标题相同(必填) String content //二级选项的内容(选填)[   {     "header": "优惠",     "isHeader": true   },   {     "isHeader": false,     "t": {       "content": "好吃的食物,增肥神器,有求必应",       "group": "优惠",       "title": "全家桶"     }   },   {     "header": "热卖",     "isHeader": true   } ]3.在布局中引入 LinkageRecyclerView 。<?xml version="1.0" encoding="utf-8"?>      4.在代码中解析 JSON,最少只需一行代码即可完成初始化。List items = gson.fromJson(...); //一行代码完成初始化 linkage.init(items);个性化配置:该库为一级和二级 Adapter 分别准备了 Config 接口(ILevelPrimaryAdapterConfig 和 ILevelSecondaryAdapterConfig),自定义配置时,即是去实现这两个接口,来取代默认的配置。之所以设置成接口的形式,而非 Builder 的形式,是因为二级联动列表内部的联动
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值