1. 程式人生 > >模仿購物車(recylerview巢狀實現)

模仿購物車(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>

主頁面的介面卡

/**
 * 展示商家的介面卡
 */
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;
            }
        }
    }
}

效果有一點和程式碼不太符合 有顏色 和位置不同 其他效果相同