模仿购物车(recylerview嵌套实现)

首先写mvp的框架

用于回调的MyCallback接口

public interface MyCallBack {
    void onSuccess(Object data);
    void onFail(Exception e);
}

model层

public interface Imodel {
    void onStarRequest(String s, Map<String,String> map, Class cals, MyCallBack myCallBack);
}

实现model

public class Imodelmpl implements Imodel {
    @Override
    public void onStarRequest(String s, Map<String, String> map, Class cals, final MyCallBack myCallBack) {
        //调用okhttp请求网络
        OkHttpUtils.getIntace().postEneque(s, map, cals, new MyCallBack() {
            @Override
            public void onSuccess(Object data) {
                myCallBack.onSuccess(data);
            }

            @Override
            public void onFail(Exception e) {
                myCallBack.onFail(e);
            }
        });
    }
}

presenter层

public interface Ipresenter {
    void onStart(String s, Map<String,String> map,Class cla);
}

实现presenter

public class IprensenterImpl implements Ipresenter {

    IView iView;
    Imodelmpl imodelmpl;


    public IprensenterImpl(IView iView) {
        this.iView=iView;
        imodelmpl=new Imodelmpl();
    }

    @Override
    public void onStart(String s, Map<String, String> map, Class cla) {
        imodelmpl.onStarRequest(s, map, cla, new MyCallBack() {
            @Override
            public void onSuccess(Object data) {
                iView.onSuccess(data);
            }

            @Override
            public void onFail(Exception e) {
                iView.onFail(e);
            }
        });
    }
    //页面销毁的时候调用
    public void onDetach(){
        if(iView!=null){
            iView=null;
        }
        if(imodelmpl!=null){
            imodelmpl=null;
        }
    }
}

 view层

public interface IView {
    void onSuccess(Object data);
    void onFail(Exception e);
}

okhttp请求网络

public class OkHttpUtils {

    private static OkHttpUtils okHttpUtils;
    private OkHttpClient mClient;
    private Handler handler=new Handler(Looper.getMainLooper());
    //单例模式 防止内存溢出
    public  static OkHttpUtils getIntace(){
        if(okHttpUtils==null){
            synchronized (OkHttpUtils.class){
                if(null==okHttpUtils){
                    okHttpUtils=new OkHttpUtils();
                }
            }
        }
        return okHttpUtils;
    }
    
    public OkHttpUtils() {
        HttpLoggingInterceptor interceptor=new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        mClient=new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .writeTimeout(10,TimeUnit.SECONDS)
                .readTimeout(10,TimeUnit.SECONDS)
                .connectTimeout(10,TimeUnit.SECONDS)
                .build();
    }
    
    //post异步请求数据
    public void postEneque(String s, Map<String,String> map, final Class clas, final MyCallBack myCallBack){
        FormBody.Builder builder=new FormBody.Builder();
        for (Map.Entry<String,String> entry:map.entrySet()){
            builder.add(entry.getKey(),entry.getValue());
        }

        RequestBody body=builder.build();
        Request request=new Request.Builder()
                .post(body)
                .url(s)
                .build();

        Call call=mClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        myCallBack.onFail(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                final Object o = new Gson().fromJson(string, clas);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        myCallBack.onSuccess(o);
                    }
                });
            }
        });
    }
}

主页面

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

    private IprensenterImpl iprensenter;
    private ShopAdapter mShopAdapter;
    private CheckBox mIvCircle;
    private List<ShopBean.DataBean> mList = new ArrayList<>();
    private TextView mAllPriceTxt, nSumPrice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_car);
        iprensenter=new IprensenterImpl(this);
        initView();
        getData();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put(Constants.MAP_KEY_GET_PRODUCT_UID, "90");
        iprensenter.onStart(Apis.URL_GET_SHOP_CAR_INFO, map, ShopBean.class);
    }

    private void initView() {
        mIvCircle = (CheckBox) findViewById(R.id.iv_cricle);
        mAllPriceTxt = (TextView) findViewById(R.id.all_price);
        nSumPrice = (TextView) findViewById(R.id.sum_price_txt);
        mIvCircle.setOnClickListener(this);

        RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mShopAdapter = new ShopAdapter(this);
        mRecyclerView.setAdapter(mShopAdapter);

        mShopAdapter.setListener(new ShopAdapter.ShopCallBackListener() {
            @Override
            public void callBack(List<ShopBean.DataBean> list) {
                //在这里重新遍历已经改状态后的数据,
                // 这里不能break跳出,因为还需要计算后面点击商品的价格和数目,所以必须跑完整个循环
                double totalPrice = 0;

                //勾选商品的数量,不是该商品购买的数量
                int num = 0;
                //所有商品总数,和上面的数量做比对,如果两者相等,则说明全选
                int totalNum = 0;
                for (int a = 0; a < list.size(); a++) {
                    //获取商家里商品
                    List<ShopBean.DataBean.ListBean> listAll = list.get(a).getList();
                    for (int i = 0; i < listAll.size(); i++) {
                        totalNum = totalNum + listAll.get(i).getNum();
                        //取选中的状态
                        if (listAll.get(i).isCheck()) {
                            totalPrice = totalPrice + (listAll.get(i).getPrice() * listAll.get(i).getNum());
                            num = num + listAll.get(i).getNum();
                        }
                    }
                }

                if (num < totalNum) {
                    //不是全部选中
                    mIvCircle.setChecked(false);
                } else {
                    //是全部选中
                    mIvCircle.setChecked(true);
                }

                mAllPriceTxt.setText("合计:" + totalPrice);
                nSumPrice.setText("去结算(" + num + ")");
            }
        });
    }

    @Override
    public void onSuccess(Object data) {
        if (data instanceof ShopBean) {
            ShopBean shopBean = (ShopBean) data;
            mList = shopBean.getData();
            if (mList != null) {
                mList.remove(0);
                mShopAdapter.setList(mList);
            }
        }
    }

    @Override
    public void onFail(Exception e) {
        Log.i("TAG",e.getLocalizedMessage());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_cricle:
                checkSeller(mIvCircle.isChecked());
                mShopAdapter.notifyDataSetChanged();
                break;
            default:
        }
    }

    private void checkSeller(boolean bool) {
        double totalPrice = 0;
        int num = 0;
        for (int a = 0; a < mList.size(); a++) {
            //遍历商家,改变状态
            ShopBean.DataBean dataBean = mList.get(a);
            dataBean.setCheck(bool);

            List<ShopBean.DataBean.ListBean> listAll = mList.get(a).getList();
            for (int i = 0; i < listAll.size(); i++) {
                //遍历商品,改变状态
                listAll.get(i).setCheck(bool);
                totalPrice = totalPrice + (listAll.get(i).getPrice() * listAll.get(i).getNum());
                num = num + listAll.get(i).getNum();
            }
        }

        if (bool) {
            mAllPriceTxt.setText("合计:" + totalPrice);
            nSumPrice.setText("去结算(" + num + ")");
        } else {
            mAllPriceTxt.setText("合计:0.00");
            nSumPrice.setText("去结算(0)");
        }

    }

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

主页面布局

<?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="match_parent"
    android:focusableInTouchMode="true"
    android:focusable="true">

    <RelativeLayout
        android:id="@+id/layout_top"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorPrimary">

        <ImageView
            android:id="@+id/iv_back"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:background="@mipmap/back"
            android:layout_centerVertical="true"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerInParent="true"
            android:text="购物车"
            android:textColor="#ffffff"
            android:textSize="16sp" />

    </RelativeLayout>

    <!--中间的显示-->
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/layout_buttom"
        android:layout_below="@+id/layout_top" />

    <!--下面的全选-->
    <RelativeLayout
        android:id="@+id/layout_buttom"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:background="#ffffff"
        android:paddingLeft="10dp">

            <CheckBox
            android:id="@+id/iv_cricle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginRight="5dp"
            android:text="全选/全不选"/>

        <TextView
            android:id="@+id/all_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="5dp"
            android:layout_toRightOf="@+id/iv_cricle"
            android:layout_toLeftOf="@+id/sum_price"
            android:text="合计:0.00"
            android:textColor="#222222"
            android:textSize="16sp" />

        <RelativeLayout
            android:id="@+id/sum_price"
            android:layout_width="100dp"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:background="@color/colorPrimary">

            <TextView
                android:id="@+id/sum_price_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="去结算(0)"
                android:textColor="#ffffff" />
        </RelativeLayout>
    </RelativeLayout>
</RelativeLayout>

主页面的适配器

扫描二维码关注公众号,回复: 4586510 查看本文章
/**
 * 展示商家的适配器
 */
public class ShopAdapter extends RecyclerView.Adapter<ShopAdapter.MyViewHolder> {
    private List<ShopBean.DataBean> mList = new ArrayList<>();
    private Context mContext;

    public ShopAdapter(Context context) {
        this.mContext = context;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = View.inflate(mContext, R.layout.shop_seller_car_adapter, null);
        MyViewHolder myViewHoler = new MyViewHolder(view);
        return myViewHoler;
    }

    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder myViewHolder, final int i) {
        //设置商家的名字
        myViewHolder.mSellerName.setText(mList.get(i).getSellerName());
        final ProductsAdapter productsAdapter = new ProductsAdapter(mContext, mList.get(i).getList());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        myViewHolder.mRecyclerView.setLayoutManager(linearLayoutManager);
        myViewHolder.mRecyclerView.setAdapter(productsAdapter);

        myViewHolder.mCheck.setChecked(mList.get(i).isCheck());

        productsAdapter.setListener(new ProductsAdapter.ShopCallBackListener() {
            @Override
            public void callBack() {
                //从商品适配里回调回来,回给activity,activity计算价格和数量
                if(mShopCallBackListener != null) {
                    mShopCallBackListener.callBack(mList);
                }

                List<ShopBean.DataBean.ListBean> listBeans = mList.get(i).getList();
                //创建一个临时的标志位,用来记录现在点击的状态
                boolean isAllChecked = true;
                for (ShopBean.DataBean.ListBean bean : listBeans) {
                    if (!bean.isCheck()) {
                        //只要有一个商品未选中,标志位设置成false,并且跳出循环
                        isAllChecked = false;
                        break;
                    }
                }

                //刷新商家的状态
                myViewHolder.mCheck.setChecked(isAllChecked);
                mList.get(i).setCheck(isAllChecked);
            }
        });

        //监听checkBox的点击事件
        //目的是改变旗下所有商品的选中状态
        myViewHolder.mCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //首先改变自己的标志位
                mList.get(i).setCheck(myViewHolder.mCheck.isChecked());
                //调用产品adapter的方法,用来全选和反选
                productsAdapter.selectOrRemoveAll(myViewHolder.mCheck.isChecked());
            }
        });
    }

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

    public void setList(List<ShopBean.DataBean> list) {
        this.mList = list;
        notifyDataSetChanged();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        RecyclerView mRecyclerView;
        TextView mSellerName;
        CheckBox mCheck;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            mSellerName = (TextView) itemView.findViewById(R.id.tv_shop);
            mCheck = itemView.findViewById(R.id.check_shop);
            mRecyclerView = (RecyclerView) itemView.findViewById(R.id.recycler_shop);
        }
    }

    private ShopCallBackListener mShopCallBackListener;

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

    public interface ShopCallBackListener {
        void callBack(List<ShopBean.DataBean> list);
    }
}

主页面的条目布局

<?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/check_shop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp" />

        <TextView
            android:id="@+id/tv_shop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_alignRight="@+id/car_circle" />
    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_shop"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/seller_name" />
</LinearLayout>

商品适配器

/**
 * 展示商家里的商品
 */
public class ProductsAdapter extends RecyclerView.Adapter<ProductsAdapter.MyViewHolder> {
    private Context mContext;
    private List<ShopBean.DataBean.ListBean> mList = new ArrayList<>();

    public ProductsAdapter(Context context, List<ShopBean.DataBean.ListBean> list) {
        this.mContext = context;
        this.mList = list;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = View.inflate(mContext, R.layout.shop_car_adapter, null);
        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i) {
        String url = mList.get(i).getImages().split("\\|")[0].replace("https", "http");
        Glide.with(mContext).load(url).into(myViewHolder.mImage);

        myViewHolder.mTitle.setText(mList.get(i).getTitle());
        myViewHolder.mPrice.setText(mList.get(i).getPrice() + "");

        //根据我记录的状态,改变勾选
        myViewHolder.mCheckBox.setChecked(mList.get(i).isCheck());

        //商品的跟商家的有所不同,商品添加了选中改变的监听
        myViewHolder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //优先改变自己的状态
                mList.get(i).setCheck(isChecked);
                //回调,目的是告诉activity,有人选中状态被改变
                if (mShopCallBackListener != null) {
                    mShopCallBackListener.callBack();
                }
            }
        });

        //设置自定义View里的Edit
        myViewHolder.mCustomShopCarPrice.setData(this, mList, i);
        myViewHolder.mCustomShopCarPrice.setOnCallBack(new CustomCounterView.CallBackListener() {
            @Override
            public void callBack() {
                if (mShopCallBackListener != null) {
                    mShopCallBackListener.callBack();
                }
            }
        });
    }

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

    public class MyViewHolder extends RecyclerView.ViewHolder {
        CustomCounterView mCustomShopCarPrice;
        TextView mTitle, mPrice;
        ImageView mImage;
        CheckBox mCheckBox;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            mImage = (ImageView) itemView.findViewById(R.id.iv_product);
            mTitle = (TextView) itemView.findViewById(R.id.tv_product_title);
            mPrice = (TextView) itemView.findViewById(R.id.tv_product_price);
            mCheckBox = (CheckBox) itemView.findViewById(R.id.check_product);
            mCustomShopCarPrice = (CustomCounterView) itemView.findViewById(R.id.custom_product_counter);
        }
    }

    /**
     * 在我们子商品的adapter中,修改子商品的全选和反选
     *
     * @param isSelectAll
     */
    public void selectOrRemoveAll(boolean isSelectAll) {
        for (ShopBean.DataBean.ListBean listBean : mList) {
            listBean.setCheck(isSelectAll);
        }

        notifyDataSetChanged();
    }

    private ShopCallBackListener mShopCallBackListener;

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

    public interface ShopCallBackListener {
        void callBack();
    }
}

商品条目的布局

<?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/check_product"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp" />

    <ImageView
        android:id="@+id/iv_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/check_product" />

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

        <TextView
            android:id="@+id/tv_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/tv_product_price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:textColor="@color/colorPrimary"
                android:textSize="12sp" />

            <com.example.yu.yuekao_demo01.View.CustomCounterView
                android:id="@+id/custom_product_counter"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/tv_product_price" />
        </RelativeLayout>
    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:layout_alignParentBottom="true"
        android:background="#cccccc" />
</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/jian_car"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_centerVertical="true"
        android:src="@mipmap/jian" />

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

    <EditText
        android:id="@+id/edit_shop_car"
        android:layout_width="50dp"
        android:layout_height="30dp"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/jian_car"
        android:background="@drawable/home_shop_bg"
        android:gravity="center"
        android:inputType="number"
        android:text="1"
        android:textSize="14sp" />
</RelativeLayout>

中间输入框的自定义样式

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#ffffff" />

    <stroke
        android:width="1dp"
        android:color="#999999" />
    <corners android:radius="30dp" />

</shape>

自定义view 代码

package com.example.yu.yuekao_demo01.View;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.yu.yuekao_demo01.R;
import com.example.yu.yuekao_demo01.ShopBean;
import com.example.yu.yuekao_demo01.adapter.ProductsAdapter;

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

public class CustomCounterView extends RelativeLayout implements View.OnClickListener {

    private EditText edit_car;
    private List<ShopBean.DataBean.ListBean> list = new ArrayList<>();
    private int position;
    private int counts;
    private ProductsAdapter productsAdapter;

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

    public CustomCounterView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CustomCounterView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private Context context;

    private void init(Context context) {
        this.context=context;
        View view=View.inflate(context,R.layout.shop_car_price_layout,null);
        ImageView addImage=view.findViewById(R.id.add_car);
        ImageView jianImage=view.findViewById(R.id.jian_car);
        edit_car = view.findViewById(R.id.edit_shop_car);
        addImage.setOnClickListener(this);
        jianImage.setOnClickListener(this);
        addView(view);

        edit_car.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) {
                //如果输入框里的内容为空  如果报异常 就把list里的数据的数量修改为0
                try {
                    counts=Integer.valueOf(String.valueOf(s));
                    list.get(position).setNum(counts);
                }catch (Exception e){
                    list.get(position).setNum(0);
                }
                if (listener!=null){
                    listener.callBack();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }



    @Override
    public void onClick(View v) {
        //点击事件
        switch (v.getId()){
            case R.id.jian_car:
                //点击减的按钮
                if(counts>1){
                    counts--;
                }else{
                    toast("我是有底线的");
                }
                list.get(position).setNum(counts);
                listener.callBack();
                productsAdapter.notifyItemChanged(position);
                break;
            case R.id.add_car:
                //点击加的按钮
                counts++;
                edit_car.setText(counts+"");
                list.get(position).setNum(counts);
                listener.callBack();
                productsAdapter.notifyItemChanged(position);
                break;
            default:break;
        }

    }

    public void toast(String msg){
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }
    //获取数据
    public void setData(ProductsAdapter productsAdapter, List<ShopBean.DataBean.ListBean> list, int i) {
        this.list = list;
        this.productsAdapter = productsAdapter;
        position = i;
        counts = list.get(i).getNum();
        edit_car.setText(counts + "");
    }


    private CallBackListener listener;

    public void setOnCallBack(CallBackListener listener) {
        this.listener = listener;
    }

    public interface CallBackListener {
        void callBack();
    }
}

bean类

package com.example.yu.yuekao_demo01;

import java.util.List;

public class ShopBean {
    private String msg;
    private String code;
    private List<DataBean> data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

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

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
        private String sellerName;
        private String sellerid;
        private List<ListBean> list;

        private boolean isCheck = false;

        public boolean isCheck() {
            return isCheck;
        }

        public void setCheck(boolean check) {
            isCheck = check;
        }

        public String getSellerName() {
            return sellerName;
        }

        public void setSellerName(String sellerName) {
            this.sellerName = sellerName;
        }

        public String getSellerid() {
            return sellerid;
        }

        public void setSellerid(String sellerid) {
            this.sellerid = sellerid;
        }

        public List<ListBean> getList() {
            return list;
        }

        public void setList(List<ListBean> list) {
            this.list = list;
        }

        public static class ListBean {
            private double bargainPrice;
            private String createtime;
            private String detailUrl;
            private String images;
            private int num;
            private int pid;
            private double price;
            private int pscid;
            private int selected;
            private int sellerid;
            private String subhead;
            private String title;

            private boolean isCheck = false;

            public boolean isCheck() {
                return isCheck;
            }

            public void setCheck(boolean check) {
                isCheck = check;
            }

            public double getBargainPrice() {
                return bargainPrice;
            }

            public void setBargainPrice(double bargainPrice) {
                this.bargainPrice = bargainPrice;
            }

            public String getCreatetime() {
                return createtime;
            }

            public void setCreatetime(String createtime) {
                this.createtime = createtime;
            }

            public String getDetailUrl() {
                return detailUrl;
            }

            public void setDetailUrl(String detailUrl) {
                this.detailUrl = detailUrl;
            }

            public String getImages() {
                return images;
            }

            public void setImages(String images) {
                this.images = images;
            }

            public int getNum() {
                return num;
            }

            public void setNum(int num) {
                this.num = num;
            }

            public int getPid() {
                return pid;
            }

            public void setPid(int pid) {
                this.pid = pid;
            }

            public double getPrice() {
                return price;
            }

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

            public int getPscid() {
                return pscid;
            }

            public void setPscid(int pscid) {
                this.pscid = pscid;
            }

            public int getSelected() {
                return selected;
            }

            public void setSelected(int selected) {
                this.selected = selected;
            }

            public int getSellerid() {
                return sellerid;
            }

            public void setSellerid(int sellerid) {
                this.sellerid = sellerid;
            }

            public String getSubhead() {
                return subhead;
            }

            public void setSubhead(String subhead) {
                this.subhead = subhead;
            }

            public String getTitle() {
                return title;
            }

            public void setTitle(String title) {
                this.title = title;
            }
        }
    }
}

效果有一点和代码不太符合 有颜色 和位置不同 其他效果相同 

猜你喜欢

转载自blog.csdn.net/xieyu1999/article/details/85105550