數(shù)據(jù)展示+購(gòu)物車(chē)

先倒入所需要依賴(lài)
 compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
    compile 'com.squareup.okhttp3:okhttp:3.1.2'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
    compile 'io.reactivex:rxjava:1.1.0'
    compile 'io.reactivex:rxandroid:1.1.0'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
    compile 'com.facebook.fresco:fresco:0.11.0'
    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    testCompile 'junit:junit:4.12'
    compile 'org.greenrobot:eventbus:3.0.0'
第一步寫(xiě)接口
public interface GoodsAPI {
    @GET("ad/getAd")
    Observable<TuiBean> Tui();
    @GET("product/getProductDetail")
    Observable<GoodsBean> get(@Query("pid") int pid);
    @GET("product/addCart?uid=2237")
    Call<ResponseBody> add(@Query("pid") int AddPid);
    @GET("product/getCarts?uid=2237")
    Observable<JiaBean> Jia();
    @GET("product/deleteCart?uid=2237")
    Call<ResponseBody> getShan(@Query("pid") int ShanPid);
}
主頁(yè)布局是一個(gè)RecyclerVie w
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
根據(jù)接口創(chuàng)建Bean類(lèi)
此步驟省略
創(chuàng)建展示數(shù)據(jù)的view
public interface ITuiView {
    void showData(List<TuiBean.TuijianBean.ListBean> list);
}
創(chuàng)建model
public interface ITuiModel {
    void showTui(Tui tui);
    interface Tui{
        void complate(List<TuiBean.TuijianBean.ListBean> list);
    }
}
public class TuiModel implements ITuiModel {

    @Override
    public void showTui(final Tui tui) {
        RetrofitApp.getInstance().Tui()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<TuiBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("======", "onError: "+e.toString());
                    }

                    @Override
                    public void onNext(TuiBean tuiBean) {
                        List<TuiBean.TuijianBean.ListBean> list= tuiBean.getTuijian().getList();
                        tui.complate(list);
                    }
                });
    }
}
封裝RetrofitApp 

public class RetrofitApp {


    private static GoodsAPI service  = null ;


    public static GoodsAPI getInstance(){
        if(service == null){
            synchronized (RetrofitApp.class){

                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://120.27.23.105/")
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .build();
                service = retrofit.create(GoodsAPI.class);
            }
        }
        return service;
    }

}
創(chuàng)建presenter

public interface IPresenter<T>{
    void attach(T view);
    void deach();
}

public class TuiPresenter implements IPresenter<ITuiView>{
    ITuiView view;
    ITuiModel model;
    SoftReference<ITuiView> reference;

    public TuiPresenter(ITuiView view) {
        attach(view);
        model = new TuiModel();
    }
    public void TuiData(){
        model.showTui(new ITuiModel.Tui() {
            @Override
            public void complate(List<TuiBean.TuijianBean.ListBean> list) {
                reference.get().showData(list);
            }
        });
    }
    @Override
    public void attach(ITuiView view) {
        reference = new SoftReference<ITuiView>(view);
    }

    @Override
    public void deach() {
        reference.clear();
    }
}
基類(lèi)
public abstract class BeasActivity<T extends IPresenter> extends Activity {
    T presenter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        createpresenter();
    }
    protected abstract void createpresenter();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter!=null){
            presenter.deach();
        }
    }
}
初始化frseco
public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Fresco.initialize(this);
    }
}
創(chuàng)建adapter
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    Context context;
    List<TuiBean.TuijianBean.ListBean> list;
    //構(gòu)造方法
    public MyAdapter(Context context, List<TuiBean.TuijianBean.ListBean> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(context, R.layout.recy_item,null);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        String images = list.get(position).getImages();
        String[] split = images.split("\\|");
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(Uri.parse(split[0]))
                .build();
        ((MyViewHolder)holder).sim.setController(controller);
        ((MyViewHolder) holder).tv.setText(list.get(position).getTitle());
        ((MyViewHolder) holder).itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int pid = list.get(position).getPid();
                Intent intent = new Intent(context, DetaActivity.class);
                intent.putExtra("pid",pid+"");
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        if (list!=null){
            return list.size();
        }
        return 0;
    }
    class MyViewHolder extends RecyclerView.ViewHolder{
        SimpleDraweeView sim;
        TextView tv;
        public MyViewHolder(View itemView) {
            super(itemView);
            sim = itemView.findViewById(R.id.sim);
            tv = itemView.findViewById(R.id.tv);
        }
    }
}
主頁(yè)Activity
public class MainActivity extends BeasActivity<TuiPresenter> implements ITuiView {
    TuiPresenter presenter;
    private RecyclerView mRv;

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

    private void initView() {
        mRv = (RecyclerView) findViewById(R.id.rv);
    }

    @Override
    protected void createpresenter() {
        presenter = new TuiPresenter(this);
    }

    @Override
    public void showData(List<TuiBean.TuijianBean.ListBean> list) {
        Log.i("=========", "showData: "+list.toString());
        GridLayoutManager mgs = new GridLayoutManager(this,2);
        mRv.setLayoutManager(mgs);
        MyAdapter adapter = new MyAdapter(this,list);
        mRv.setAdapter(adapter);
    }
}
接下來(lái)肩祥。就是點(diǎn)擊詳情
首先较雕。還是解析一個(gè)bean類(lèi)轧膘。此步驟省略
布局
<com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/oo_sim"
        android:layout_width="match_parent"
        android:layout_height="600dp" />
    <TextView
        android:id="@+id/oo_tv"
        android:layout_below="@+id/oo_sim"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/btn"
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:text="加入購(gòu)物車(chē)"
        android:background="#ff0000"
        android:textColor="#ffffff"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"/>
創(chuàng)建View層
public interface IGoodsView {
    void showData(GoodsBean bean);
    int pid();
}
創(chuàng)建model層
 public interface IGoodsModel {
    void showGoods(int pid,Goods goods);
    interface Goods{
        void complate(GoodsBean bean);
    }
}
public class GoodsModel implements IGoodsModel {
    @Override
    public void showGoods(int pid, final Goods goods) {
        RetrofitUtils.getInstance().get(pid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GoodsBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("=======", "onError: "+e.toString());
                    }

                    @Override
                    public void onNext(GoodsBean bean) {
                        goods.complate(bean);
                    }
                });
    }
}
接口
public class RetrofitUtils {


    private static GoodsAPI service  = null ;


    public static GoodsAPI getInstance(){
        if(service == null){
            synchronized (RetrofitUtils.class){

                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://120.27.23.105/")
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .client(OkHttpUtils.getInstance())
                        .build();
                service = retrofit.create(GoodsAPI.class);
            }
        }
        return service;
    }

}
創(chuàng)建presenter
public class GoodsPresenter implements IPresenter<IGoodsView>{
    IGoodsView view;
    IGoodsModel model;
    SoftReference<IGoodsView> reference;

    public GoodsPresenter(IGoodsView view) {
        attach(view);
        model = new GoodsModel();
    }
    public void GoodsData(){
        int pid = reference.get().pid();
        model.showGoods(pid, new IGoodsModel.Goods() {
            @Override
            public void complate(GoodsBean bean) {
                reference.get().showData(bean);
            }
        });
    }
    @Override
    public void attach(IGoodsView view) {
        reference = new SoftReference<IGoodsView>(view);
    }

    @Override
    public void deach() {
        reference.clear();
    }
}
最后Adpter
public class DetaActivity extends BeasActivity<GoodsPresenter> implements IGoodsView, View.OnClickListener {
    //全局變量
    GoodsPresenter presenter;
    int i;
    private SimpleDraweeView mSimOo;
    private TextView mTvOo;
    private Button mBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deta);
        initView();
        String Sid = getIntent().getStringExtra("pid");
        i = Integer.parseInt(Sid);
        presenter.GoodsData();
    }

    //找控件
    private void initView() {
        mSimOo = (SimpleDraweeView) findViewById(R.id.oo_sim);
        mTvOo = (TextView) findViewById(R.id.oo_tv);
        mBtn = (Button) findViewById(R.id.btn);
        mBtn.setOnClickListener(this);
    }

    @Override
    protected void createpresenter() {
        presenter = new GoodsPresenter(this);

    }

    //p層方法
    @Override
    public void showData(GoodsBean bean) {
        String images = bean.getData().getImages();
        String[] split = images.split("\\|");
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(Uri.parse(split[0]))
                .build();
        mSimOo.setController(controller);
        mTvOo.setText(bean.getData().getTitle());
        EventBus.getDefault().post(new MessageEvent(bean.getData().getPid()));
    }

    @Override
    public int pid() {
        return i;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn:
                Call<ResponseBody> call =  RetrofitAPI.getInstance().add(i);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        Toast.makeText(DetaActivity.this,"添加",Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(DetaActivity.this,JiaActivity.class);
                        intent.putExtra("pid",i+"");
                        startActivity(intent);
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Toast.makeText(DetaActivity.this,"失敗",Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            default:
                break;
        }
    }



    /*@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn:

                Intent intent  = new Intent(DetaActivity.this,JiaActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }*/
}
購(gòu)物車(chē)的bean類(lèi)灯节。還是省略
布局
activity_jia
<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="20dp"
        >
        <TextView
            android:id="@+id/jia_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:text="編輯"/>
        <TextView
            android:id="@+id/jia_tv2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:visibility="gone"
            android:text="完成"/>
    </RelativeLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_View"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        />

    <LinearLayout
        android:gravity="center_vertical"
        android:padding="10dp"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <CheckBox
            android:background="@drawable/shopcart_unselected"
            android:button="@null"
            android:id="@+id/quanxuan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:textStyle="bold"
            android:layout_marginLeft="10dp"
            android:textSize="23sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="全選"
            />

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

            <TextView
                android:textColor="#e53e42"
                android:id="@+id/total_price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:text="總價(jià) : ¥0元"
                />

            <TextView
                android:id="@+id/total_num"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:text="共0件商品"
                />

        </LinearLayout>
        <TextView
            android:id="@+id/shanchu"
            android:gravity="center"
            android:textSize="25sp"
            android:text="刪除"
            android:textColor="#fff"
            android:visibility="gone"
            android:background="@drawable/qujiesuan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/jiesuan"
            android:gravity="center"
            android:textSize="25sp"
            android:text="去結(jié)算"
            android:textColor="#fff"
            android:background="@drawable/qujiesuan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
自定義布局
custom_jiajian
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <Button
        android:background="#fff"
        android:textSize="20sp"
        android:id="@+id/reverse"
        android:text="一"
        android:layout_width="50dp"
        android:layout_height="wrap_content" />

    <EditText
        android:textStyle="bold"
        android:textSize="23sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1"
        android:id="@+id/count"
        />

    <Button
        android:id="@+id/add"
        android:background="#fff"
        android:textSize="25sp"
        android:text="+"
        android:layout_width="50dp"
        android:layout_height="wrap_content" />
</LinearLayout>
商店布局
rely_cart_item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:padding="15dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <CheckBox
            android:id="@+id/shop_checkbox"
            android:layout_width="50dp"
            android:layout_height="50dp" />

        <TextView
            android:layout_marginLeft="20dp"
            android:text="良品鋪?zhàn)?
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="23sp"
            android:textStyle="bold"
            android:id="@+id/shop_name"
            />
    </LinearLayout>

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

        <CheckBox
            android:id="@+id/item_checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <com.facebook.drawee.view.SimpleDraweeView
            android:id="@+id/item_face"
            android:src="@mipmap/ic_launcher"
            fresco:failureImageScaleType="centerInside"
            android:layout_width="120dp"
            android:layout_height="120dp" />

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

            <TextView
                android:id="@+id/item_name"
                android:textSize="20sp"
                android:text="三只松鼠"
                android:layout_width="wrap_content"
                android:layout_weight="1"
                android:layout_height="0dp"
                />

            <TextView
                android:textColor="#f00"
                android:id="@+id/item_price"
                android:textSize="23sp"
                android:text="299"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_weight="1"
                />


            <com.example.mx.miaoxinzhoukao3.utils.CustomJiaJian
                android:id="@+id/custom_jiajian"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_weight="1"
                />
        </LinearLayout>

        <ImageView
            android:id="@+id/item_delete"
            android:layout_marginRight="10dp"
            android:src="@mipmap/ic_launcher"
            android:layout_width="30dp"
            android:layout_height="30dp" />
    </LinearLayout>
</LinearLayout>
 創(chuàng)建view
public interface IJiaView {
    void showData(JiaBean bean);
}
創(chuàng)建model
public interface IJiaModel {
    void showJia(Jia jia);
    interface Jia{
        void complate(JiaBean bean);
    }
}
public class JiaModel implements IJiaModel {
    @Override
    public void showJia(final Jia jia) {
        RetrofitUtils.getInstance().Jia()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JiaBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(JiaBean bean) {
                        jia.complate(bean);
                    }
                });
    }
}
接口
public class RetrofitUtils {


    private static GoodsAPI service  = null ;


    public static GoodsAPI getInstance(){
        if(service == null){
            synchronized (RetrofitUtils.class){

                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://120.27.23.105/")
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .client(OkHttpUtils.getInstance())
                        .build();
                service = retrofit.create(GoodsAPI.class);
            }
        }
        return service;
    }

}
創(chuàng)建presenter
public class JiaPresenter implements IPresenter<IJiaView> {
    IJiaView view;
    IJiaModel model;
    SoftReference<IJiaView> reference;

    public JiaPresenter(IJiaView view) {
        attach(view);
        model = new JiaModel();
    }
    public void JiaData(){
        model.showJia(new IJiaModel.Jia() {
            @Override
            public void complate(JiaBean bean) {
                reference.get().showData(bean);
            }
        });
    }
    @Override
    public void attach(IJiaView view) {
        reference = new SoftReference<IJiaView>(view);
    }

    @Override
    public void deach() {
        reference.clear();
    }
}
創(chuàng)建adapter
public class RecyAdapter extends RecyclerView.Adapter<RecyAdapter.MyViewHolder>{
    JiaActivity jiaActivity;
    Context context;
    List<Integer> listint=new ArrayList<>();
    //創(chuàng)建大的集合
    private List<JiaBean.DataBean.ListBean> list;

    //存放商家的id和商家的名稱(chēng)的map集合
    private Map<String,String> map = new HashMap<>();

    public RecyAdapter(Context context, JiaActivity jiaActivity) {
        this.context = context;
        this.jiaActivity=jiaActivity;
    }

    /**
     * 添加數(shù)據(jù)并更新顯示
     * */
    public void add(JiaBean cartBean){
        //傳進(jìn)來(lái)的是bean對(duì)象
        if(list == null){
            list = new ArrayList<>();
        }
        //第一層遍歷商家和商品
        for (JiaBean.DataBean shop : cartBean.getData()){
            //把商品的id和商品的名稱(chēng)添加到map集合里 ,,為了之后方便調(diào)用
            map.put(shop.getSellerid(),shop.getSellerName());
            //第二層遍歷里面的商品
            for (int i=0;i<shop.getList().size();i++){
                //添加到list集合里
                list.add(shop.getList().get(i));
            }
        }
        //調(diào)用方法 設(shè)置顯示或隱藏 商鋪名
        setFirst(list);
        notifyDataSetChanged();
    }

    /**
     * 設(shè)置數(shù)據(jù)源,控制是否顯示商家
     * */
    private void setFirst(List<JiaBean.DataBean.ListBean> list) {

        if(list.size()>0){
            //如果是第一條數(shù)據(jù)就設(shè)置isFirst為1
            list.get(0).setIsFirst(1);
            //從第二條開(kāi)始遍歷
            for (int i=1;i<list.size();i++){
                //如果和前一個(gè)商品是同一家商店的
                if (list.get(i).getSellerid() == list.get(i-1).getSellerid()){
                    //設(shè)置成2不顯示商鋪
                    list.get(i).setIsFirst(2);
                }else{//設(shè)置成1顯示商鋪
                    list.get(i).setIsFirst(1);
                    //如果當(dāng)前條目選中,把當(dāng)前的商鋪也選中
                    if (list.get(i).isItem_check()==true){
                        list.get(i).setShop_check(list.get(i).isItem_check());
                    }
                }
            }
        }
    }

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

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        //判斷是否選中

            if(list.get(position).isItem_check()==true){
                listint.add(position);
                Log.i("listssssss", "onBindViewHolder: "+listint.toString());
                jiaActivity.getdeletetv().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                            Call<ResponseBody> call = RetrofitUtils.getInstance().getShan(list.get(position).getPid());
                            call.enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    Toast.makeText(context,"刪除",Toast.LENGTH_SHORT).show();
                                    notifyDataSetChanged();
                                }

                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {
                                    Toast.makeText(context,"失敗",Toast.LENGTH_SHORT).show();
                                }
                            });
                            list.remove(position);
                            sum(list);
                            notifyDataSetChanged();
                        }
                });
            }


        /**
         * 設(shè)置商鋪的 shop_checkbox和商鋪的名字 顯示或隱藏
         * */
        if(list.get(position).getIsFirst()==1){
            //顯示商家
            holder.shop_checkbox.setVisibility(View.VISIBLE);
            holder.shop_name.setVisibility(View.VISIBLE);
            //設(shè)置shop_checkbox的選中狀態(tài)
            holder.shop_checkbox.setChecked(list.get(position).isShop_check());
            holder.shop_name.setText(map.get(String.valueOf(list.get(position).getSellerid())));
        }else{//2
            //隱藏商家
            holder.shop_name.setVisibility(View.GONE);
            holder.shop_checkbox.setVisibility(View.GONE);
        }

        //拆分images字段
        String images = list.get(position).getImages();
        String[] split = images.split("\\|");
        //設(shè)置商品的圖片
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(Uri.parse(split[0]))
                .build();
        holder.item_face.setController(controller);
        //控制商品的item_checkbox,,根據(jù)字段改變
        holder.item_checkbox.setChecked(list.get(position).isItem_check());
        holder.item_name.setText(list.get(position).getTitle());
        holder.item_price.setText(list.get(position).getPrice()+"");
        //調(diào)用customjiajian里面的方法設(shè)置 加減號(hào)中間的數(shù)字
        holder.customJiaJian.setEditText(list.get(position).getNum());

        //商鋪的shop_checkbox點(diǎn)擊事件 ,控制商品的item_checkbox
        holder.shop_checkbox.setOnClickListener(  new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //先改變數(shù)據(jù)源中的shop_check
                list.get(position).setShop_check(holder.shop_checkbox.isChecked());

                for (int i=0;i<list.size();i++){
                    //如果是同一家商鋪的 都給成相同狀態(tài)
                    if(list.get(position).getSellerid()==list.get(i).getSellerid()){
                        //當(dāng)前條目的選中狀態(tài) 設(shè)置成 當(dāng)前商鋪的選中狀態(tài)
                        list.get(i).setItem_check(holder.shop_checkbox.isChecked());
                    }
                }
                //刷新適配器
                notifyDataSetChanged();
                //調(diào)用求和的方法
                sum(list);
            }
        });

        //商品的item_checkbox點(diǎn)擊事件,控制商鋪的shop_checkbox
        holder.item_checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(holder.item_checkbox.isChecked()){
                    list.get(position).setItem_check(true);
                }
                //先改變數(shù)據(jù)源中的item_checkbox
                list.get(position).setItem_check(holder.item_checkbox.isChecked());

                //反向控制商鋪的shop_checkbox
                for (int i=0;i<list.size();i++){
                    for (int j=0;j<list.size();j++){
                        //如果兩個(gè)商品是同一家店鋪的 并且 這兩個(gè)商品的item_checkbox選中狀態(tài)不一樣
                        if(list.get(i).getSellerid()==list.get(j).getSellerid() && !list.get(j).isItem_check()){
                            //就把商鋪的shop_checkbox改成false
                            list.get(i).setShop_check(false);
                            break;
                        }else{
                            //同一家商鋪的商品 選中狀態(tài)都一樣,就把商鋪shop_checkbox狀態(tài)改成true
                            list.get(i).setShop_check(true);
                        }
                    }
                }

                //更新適配器
                notifyDataSetChanged();
                //調(diào)用求和的方法
                sum(list);
            }
        });

        //刪除條目的點(diǎn)擊事件
        holder.item_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.remove(position);//移除集合中的當(dāng)前數(shù)據(jù)
                //刪除完當(dāng)前的條目 重新判斷商鋪的顯示隱藏
                setFirst(list);

                //調(diào)用重新求和
                sum(list);
                notifyDataSetChanged();
            }
        });

        //加減號(hào)的監(jiān)聽(tīng),
        holder.customJiaJian.setCustomListener(new CustomJiaJian.CustomListener() {
            @Override
            public void jiajian(int count) {
                //改變數(shù)據(jù)源中的數(shù)量
                list.get(position).setNum(count);
                notifyDataSetChanged();
                sum(list);
            }

            @Override
            //輸入值 求總價(jià)
            public void shuRuZhi(int count) {
                list.get(position).setNum(count);
                notifyDataSetChanged();
                sum(list);
            }
        });
    }

    /**
     * 計(jì)算總價(jià)的方法
     * */
    private void sum(List<JiaBean.DataBean.ListBean> list){
        int totalNum = 0;//初始的總價(jià)為0
        float totalMoney = 0.0f;
        boolean allCheck = true;
        for (int i=0;i<list.size();i++){
            //把 已經(jīng)選中的 條目 計(jì)算價(jià)格
            if (list.get(i).isItem_check()){
                totalNum += list.get(i).getNum();
                totalMoney += list.get(i).getNum() * list.get(i).getPrice();
            }else{
                //如果有個(gè)未選中,就標(biāo)記為false
                allCheck = false;
            }
        }

        //接口回調(diào)出去 把總價(jià) 總數(shù)量 和allcheck 傳給view層
        updateListener.setTotal(totalMoney+"",totalNum+"",allCheck);
    }

    //view層調(diào)用這個(gè)方法, 點(diǎn)擊quanxuan按鈕的操作
    public void quanXuan(boolean checked) {
        for (int i=0;i<list.size();i++){
            list.get(i).setShop_check(checked);
            list.get(i).setItem_check(checked);

        }
        notifyDataSetChanged();
        sum(list);
    }

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



    public static class MyViewHolder extends RecyclerView.ViewHolder {

        private final CheckBox shop_checkbox;
        private final TextView shop_name;
        private final CheckBox item_checkbox;
        private final TextView item_name;
        private final TextView item_price;
        private final CustomJiaJian customJiaJian;
        private final ImageView item_delete;
        private final SimpleDraweeView item_face;

        public MyViewHolder(View itemView) {
            super(itemView);
            shop_checkbox = (CheckBox) itemView.findViewById(R.id.shop_checkbox);
            shop_name = (TextView) itemView.findViewById(R.id.shop_name);
            item_checkbox = (CheckBox) itemView.findViewById(R.id.item_checkbox);
            item_name = (TextView) itemView.findViewById(R.id.item_name);
            item_price = (TextView) itemView.findViewById(R.id.item_price);
            customJiaJian = (CustomJiaJian) itemView.findViewById(R.id.custom_jiajian);
            item_delete = (ImageView) itemView.findViewById(R.id.item_delete);
            item_face = (SimpleDraweeView) itemView.findViewById(R.id.item_face);
        }
    }

    UpdateListener updateListener;
    public void setUpdateListener(UpdateListener updateListener){
        this.updateListener = updateListener;
    }
    //接口
    public interface UpdateListener{
        public void setTotal(String total,String num,boolean allCheck);
    }
}
自定義控件
public class CustomJiaJian extends LinearLayout {
    private Button reverse;
    private Button add;
    private EditText countEdit;
    private int mCount =1;
    public CustomJiaJian(Context context) {
        super(context);
    }

    public CustomJiaJian(final Context context, AttributeSet attrs) {
        super(context, attrs);
        View view = View.inflate(context, R.layout.custom_jiajian,this);

        reverse = (Button) view.findViewById(R.id.reverse);
        add = (Button) view.findViewById(R.id.add);
        countEdit = (EditText) view.findViewById(R.id.count);

        reverse.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = countEdit.getText().toString().trim();
                int count = Integer.valueOf(content);

                if(count>1){
                    mCount = count-1;
                    countEdit.setText(mCount+"");
                    //回調(diào)給adapter里面
                    if(customListener!=null){
                        customListener.jiajian(mCount);
                    }
                }
                if (count==1){
                    Toast.makeText(context,"最小只能為一",Toast.LENGTH_SHORT).show();
                }
            }
        });

        add.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = countEdit.getText().toString().trim();
                int count = Integer.valueOf(content)+1;
                mCount = count;

                countEdit.setText(mCount+"");

                //接口回調(diào)給adapter
                if(customListener!=null){
                    customListener.jiajian(mCount);
                }
            }
        });

    }

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

    CustomListener customListener;
    public void setCustomListener(CustomListener customListener){
        this.customListener = customListener;
    }

    //加減的接口
    public interface CustomListener{
        public void jiajian(int count);
        public void shuRuZhi(int count);
    }

    //這個(gè)方法是供recyadapter設(shè)置 數(shù)量時(shí)候調(diào)用的
    public void setEditText(int num) {
        if(countEdit !=null) {
            countEdit.setText(num + "");
        }
    }
}
jiaAc tivity
public class JiaActivity extends BeasActivity<JiaPresenter> implements IJiaView, View.OnClickListener {
    JiaPresenter presenter;
    private RecyclerView mViewRecycler;
    private CheckBox mQuanxuan;
    private TextView mPriceTotal;
    private TextView mNumTotal;
    private RecyAdapter recyAdapter;
    private TextView mTvJia;
    private TextView mTv2Jia;
    private TextView mShanchu;
    private TextView mJiesuan;
    int pid;
    List<JiaBean.DataBean.ListBean> list = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jia);
        initView();
        String Sid = getIntent().getStringExtra("pid");
        pid = Integer.parseInt(Sid);
        presenter.JiaData();
    }
    public TextView getdeletetv(){
        return mShanchu;
    }
    private void initView() {

        mViewRecycler = (RecyclerView) findViewById(R.id.recycler_View);
        mQuanxuan = (CheckBox) findViewById(R.id.quanxuan);
        mPriceTotal = (TextView) findViewById(R.id.total_price);
        mNumTotal = (TextView) findViewById(R.id.total_num);
        mQuanxuan.setTag(1);//1為不選中
        LinearLayoutManager manager = new LinearLayoutManager(JiaActivity.this, LinearLayoutManager.VERTICAL, false);
        //new出適配器
        recyAdapter = new RecyAdapter(this,this);
        mViewRecycler.setLayoutManager(manager);
        mViewRecycler.setAdapter(recyAdapter);
        recyAdapter.setUpdateListener(new RecyAdapter.UpdateListener() {
            @Override
            public void setTotal(String total, String num, boolean allCheck) {
                //設(shè)置ui的改變
                mNumTotal.setText("共" + num + "件商品");//總數(shù)量
                mPriceTotal.setText("總價(jià) :¥" + total + "元");//總價(jià)
                if (allCheck) {
                    mQuanxuan.setTag(2);
                    mQuanxuan.setBackgroundResource(R.drawable.shopcart_selected);
                } else {
                    mQuanxuan.setTag(1);
                    mQuanxuan.setBackgroundResource(R.drawable.shopcart_unselected);
                }
                mQuanxuan.setChecked(allCheck);
            }
        });
        //這里只做ui更改, 點(diǎn)擊全選按鈕,,調(diào)到adapter里面操作
        mQuanxuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //調(diào)用adapter里面的方法 ,,把當(dāng)前quanxuan狀態(tài)傳遞過(guò)去

                int tag = (int) mQuanxuan.getTag();
                if (tag == 1) {
                    mQuanxuan.setTag(2);
                    mQuanxuan.setBackgroundResource(R.drawable.shopcart_selected);
                } else {
                    mQuanxuan.setTag(1);
                    mQuanxuan.setBackgroundResource(R.drawable.shopcart_unselected);
                }

                recyAdapter.quanXuan(mQuanxuan.isChecked());
            }
        });
        mTvJia = (TextView) findViewById(R.id.jia_tv);
        mTv2Jia = (TextView) findViewById(R.id.jia_tv2);
        mShanchu = (TextView) findViewById(R.id.shanchu);
        mJiesuan = (TextView) findViewById(R.id.jiesuan);
        mTvJia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTv2Jia.setVisibility(View.VISIBLE);
                mTvJia.setVisibility(View.GONE);
                mShanchu.setVisibility(View.VISIBLE);
                mJiesuan.setVisibility(View.GONE);
            }
        });
        mTv2Jia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvJia.setVisibility(View.VISIBLE);
                mTv2Jia.setVisibility(View.GONE);
                mShanchu.setVisibility(View.GONE);
                mJiesuan.setVisibility(View.VISIBLE);
            }
        });
        mShanchu.setOnClickListener(this);
    }

    @Override
    protected void createpresenter() {
        presenter = new JiaPresenter(this);
    }
    @Override
    public void showData(JiaBean bean) {
        recyAdapter.add(bean);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.shanchu:
                Call<ResponseBody> call = RetrofitUtils.getInstance().getShan(pid);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        Toast.makeText(JiaActivity.this,"刪除",Toast.LENGTH_SHORT).show();
                        recyAdapter.notifyDataSetChanged();
                    }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                Toast.makeText(JiaActivity.this,"失敗",Toast.LENGTH_SHORT).show();
            }
        });
                break;
            default:
                break;
        }
    }
}



?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末猾警,一起剝皮案震驚了整個(gè)濱河市妨蛹,隨后出現(xiàn)的幾起案子拆讯,更是在濱河造成了極大的恐慌脂男,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,602評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件种呐,死亡現(xiàn)場(chǎng)離奇詭異宰翅,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)爽室,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,442評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)汁讼,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人阔墩,你說(shuō)我怎么就攤上這事嘿架。” “怎么了啸箫?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,878評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵耸彪,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我忘苛,道長(zhǎng)蝉娜,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,306評(píng)論 1 279
  • 正文 為了忘掉前任柑土,我火速辦了婚禮蜀肘,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘稽屏。我一直安慰自己,他們只是感情好西乖,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,330評(píng)論 5 373
  • 文/花漫 我一把揭開(kāi)白布狐榔。 她就那樣靜靜地躺著坛增,像睡著了一般。 火紅的嫁衣襯著肌膚如雪薄腻。 梳的紋絲不亂的頭發(fā)上收捣,一...
    開(kāi)封第一講書(shū)人閱讀 49,071評(píng)論 1 285
  • 那天,我揣著相機(jī)與錄音庵楷,去河邊找鬼罢艾。 笑死,一個(gè)胖子當(dāng)著我的面吹牛尽纽,可吹牛的內(nèi)容都是我干的咐蚯。 我是一名探鬼主播,決...
    沈念sama閱讀 38,382評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼弄贿,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼春锋!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起差凹,我...
    開(kāi)封第一講書(shū)人閱讀 37,006評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤期奔,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后危尿,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體呐萌,經(jīng)...
    沈念sama閱讀 43,512評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,965評(píng)論 2 325
  • 正文 我和宋清朗相戀三年谊娇,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了肺孤。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,094評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡邮绿,死狀恐怖渠旁,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情船逮,我是刑警寧澤顾腊,帶...
    沈念sama閱讀 33,732評(píng)論 4 323
  • 正文 年R本政府宣布,位于F島的核電站挖胃,受9級(jí)特大地震影響杂靶,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜酱鸭,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,283評(píng)論 3 307
  • 文/蒙蒙 一吗垮、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧凹髓,春花似錦烁登、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,286評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)锨络。三九已至,卻和暖如春狼牺,著一層夾襖步出監(jiān)牢的瞬間羡儿,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,512評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工是钥, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留掠归,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,536評(píng)論 2 354
  • 正文 我出身青樓悄泥,卻偏偏與公主長(zhǎng)得像虏冻,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子码泞,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,828評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容