购物车代码

本文详细探讨了在线购物车的实现原理,从需求分析到功能模块设计,涵盖了数据存储、商品增删改查、数量调整及总价计算等关键点。通过实例代码解析,帮助读者理解购物车系统的背后逻辑。
摘要由CSDN通过智能技术生成
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'io.reactivex.rxjava2:rxjava:2.1.7'
    compile 'com.facebook.fresco:fresco:0.12.0'
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
    compile 'com.squareup.retrofit2:converter-scalars:2.0.0'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
    compile 'com.google.code.gson:gson:2.8.2'
    compile 'com.squareup.okhttp3:okhttp:3.9.0'
    compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'

}

以上便是导入的依赖

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <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/c"
            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="总价 : ¥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:gravity="center"
            android:textSize="25sp"
            android:text="去结算"
            android:textColor="#fff"
            android:background="@drawable/qujiesuan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>
以上是main-activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    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>

以上是cuou

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:padding="15dp"
    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="良品铺子"
            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"
            fresco:placeholderImage="@mipmap/ic_launcher"
            fresco:progressBarImage="@mipmap/ic_launcher"
            fresco:progressBarImageScaleType="centerInside"
            fresco:failureImage="@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.gouwuche.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="@drawable/a"
            android:layout_width="30dp"
            android:layout_height="30dp" />
    </LinearLayout>
</LinearLayout>
以上是自己item的文件

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

    <corners android:radius="200dp"/>
    <solid android:color="#e53e42"/>
    <size android:height="60dp" android:width="130dp"/>
</shape>
这个是自定义的daellc

package com.example.gouwuche.util;

import android.content.Context;

import com.facebook.cache.disk.DiskCacheConfig;
import com.facebook.common.internal.Supplier;
import com.facebook.common.util.ByteConstants;
import com.facebook.imagepipeline.cache.MemoryCacheParams;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.facebook.imagepipeline.listener.RequestListener;
import com.facebook.imagepipeline.listener.RequestLoggingListener;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by D-H-F on 2017/12/11.
 */

public class ImagePipelineConfigFactory {
    private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory();
    public static final int MAX_DISK_CACHE_SIZE = 40 * ByteConstants.MB;
    public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4;
    private static final String IMAGE_PIPELINE_CACHE_DIR = "imagepipeline_cache";


    private static void configureCaches(
            ImagePipelineConfig.Builder configBuilder,
            Context context) {
        final MemoryCacheParams bitmapCacheParams = new MemoryCacheParams(
                MAX_MEMORY_CACHE_SIZE, // Max total size of elements in the cache
                Integer.MAX_VALUE,                     // Max entries in the cache
                MAX_MEMORY_CACHE_SIZE, // Max total size of elements in eviction queue
                Integer.MAX_VALUE,                     // Max length of eviction queue
                Integer.MAX_VALUE);                    // Max cache entry size
        configBuilder
                .setBitmapMemoryCacheParamsSupplier(
                        new Supplier<MemoryCacheParams>() {
                            public MemoryCacheParams get() {
                                return bitmapCacheParams;
                            }
                        })
                .setMainDiskCacheConfig(
                        DiskCacheConfig.newBuilder(context)
                                .setBaseDirectoryPath(context.getApplicationContext().getCacheDir())
                                .setBaseDirectoryName(IMAGE_PIPELINE_CACHE_DIR)
                                .setMaxCacheSize(MAX_DISK_CACHE_SIZE)
                                .build());
    }

    private static void configureLoggingListeners(ImagePipelineConfig.Builder configBuilder) {
        Set<RequestListener> requestListeners = new HashSet<>();
        requestListeners.add(new RequestLoggingListener());
        configBuilder.setRequestListeners(requestListeners);
    }

    private static void configureOptions(ImagePipelineConfig.Builder configBuilder) {
        configBuilder.setDownsampleEnabled(true);
    }

}
这个便是自己

package com.example.gouwuche.util;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

/**
 * Created by D-H-F on 2017/12/11.
 */

public class OkHttpUtils {

    private static OkHttpClient client = null;

    public static  OkHttpClient getInstance(){

        if(client==null){
            synchronized (OkHttpUtils.class){
                if(client==null){
                    client =  new OkHttpClient.Builder()
                            .connectTimeout(2000, TimeUnit.SECONDS)
                            .writeTimeout(2000,TimeUnit.SECONDS)
                            .readTimeout(2000,TimeUnit.SECONDS)
                            .build();
                }

            }
        }

        return client;
    }
}
以上是okhttp的类

package com.example.gouwuche.util;


import com.example.gouwuche.other.IGetService;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by D-H-F on 2017/12/11.
 */

public class RetrofitUtils {
    private  static IGetService server =null;

    public  static  IGetService getInstance(){
        if(server==null){
            synchronized (RetrofitUtils.class){
                if(server==null){
                    Retrofit build = new Retrofit.Builder()
                            .baseUrl("http://120.27.23.105")
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .client(OkHttpUtils.getInstance())
                            .build();
                    server = build.create(IGetService.class);
                }
            }
        }
        return server;
    }
}
以上是自己retrofit的类

package com.example.gouwuche;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

/**
 * Created by HP on 2017/12/11.
 */
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(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+"");
                    //回调给adapter里面
                    if(customListener!=null){
                        customListener.jiajian(mCount);
                    }
                }
            }
        });

        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+"");

                //接口回调给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);
    }

    //这个方法是供recyadapter设置 数量时候调用的
    public void setEditText(int num) {
        if(countEdit !=null) {
            countEdit.setText(num + "");
        }
    }
}
这个便是自己定义的加减的值

package com.example.gouwuche.bean;

/**
 * Created by HP on 2017/12/11.
 */

public class DelBean {
    /**
     * msg : 删除购物车成功
     * code : 0
     */

    private String msg;
    private String code;

    @Override
    public String toString() {
        return "DelBean{" +
                "msg='" + msg + '\'' +
                ", code='" + code + '\'' +
                '}';
    }

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

DelBean类
package com.example.gouwuche.model;


import com.example.gouwuche.bean.DelBean;
import com.example.gouwuche.util.RetrofitUtils;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by D-H-F on 2017/12/11.
 */

public class DelModel {


    public DelModel(String s, int pid, final DelModelInterface delModelInterface) {

        RetrofitUtils.getInstance().Del(s,pid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DelBean>() {
                    @Override
                    public void accept(DelBean delBean) throws Exception {
                        delModelInterface.Success(delBean);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        System.out.println("throwable1111111111111 = " + throwable);
                        delModelInterface.Fail();
                    }
                });



    }

    public interface DelModelInterface{

            void Success(DelBean bean);
            void Fail();

    }
}

DelModel类
package com.example.gouwuche.model;

import com.example.gouwuche.bean.Bean;
import com.example.gouwuche.util.RetrofitUtils;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by D-H-F on 2017/12/11.
 */

public class LoginModel {


    public void getData(final LoginModelInterface loginModelInterface) {

        RetrofitUtils.getInstance().get("100")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bean>() {
                    @Override
                    public void accept(Bean bean) throws Exception {

                        System.out.println("bean = " + bean.toString());

                        loginModelInterface.Success(bean);

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                        System.out.println("throwable = " + throwable);
                        loginModelInterface.Fail();
                    }
                });

    }

    public  interface LoginModelInterface{

        void Success(Bean bean);

        void Fail();
    }
}

LoginModel类
package com.example.gouwuche.other;

import android.app.Application;

import com.facebook.drawee.backends.pipeline.Fresco;

/**
 * Created by D-H-F on 2017/12/11.
 */

public class IApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Fresco.initialize(this);

    }
}

IApplication类初试化fresco
package com.example.gouwuche.other;


import com.example.gouwuche.bean.Bean;
import com.example.gouwuche.bean.DelBean;

import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query;

/**
 * Created by D-H-F on 2017/12/11.
 */

public interface IGetService {

    @GET("/product/getCarts")

    Observable<Bean> get(@Query("uid") String v);

    @GET("/product/deleteCart")
    Observable<DelBean> Del(@Query("uid") String v, @Query("pid") int i);
}

IGetService类接口

package com.example.gouwuche.present;

import com.example.gouwuche.MainActivity;
import com.example.gouwuche.bean.DelBean;
import com.example.gouwuche.model.DelModel;


/**
 * Created by D-H-F on 2017/12/11.
 */

public class DelPresent {
    MainActivity mainActivity;
    public DelPresent(MainActivity mainActivity) {
        this.mainActivity=mainActivity;
    }

    public void get(String s, int pid) {

        new DelModel(s,pid, new DelModel.DelModelInterface() {
            @Override
            public void Success(DelBean bean) {
                mainActivity.Success(bean);
            }

            @Override
            public void Fail() {
                mainActivity.Fail();
            }
        });

    }

    public interface DelPresentInterface{
        void Success(DelBean bean);
        void Fail();
    }
}

DelPresent类
package com.example.gouwuche.present;


import com.example.gouwuche.MainActivity;
import com.example.gouwuche.bean.Bean;
import com.example.gouwuche.model.LoginModel;

/**
 * Created by D-H-F on 2017/12/11.
 */

public class LoginPresent {

    MainActivity mainActivity;
    LoginModel loginModel;
    public LoginPresent(MainActivity mainActivity) {
        this.mainActivity=mainActivity;
        this.loginModel=new LoginModel();
    }

    public void get() {
        loginModel.getData(new LoginModel.LoginModelInterface() {
            @Override
            public void Success(Bean bean) {
                mainActivity.Success(bean);
            }
            @Override
            public void Fail() {
                mainActivity.Fail();
            }
        });
    }

    public void detach() {

        mainActivity=null;
    }

    public  interface LoginPresentInterface{

        void Success(Bean bean);

        void Fail();
    }
}

LoginPresent类

package com.example.gouwuche;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.example.gouwuche.adapter.RecAdapter;
import com.example.gouwuche.bean.Bean;
import com.example.gouwuche.bean.DelBean;
import com.example.gouwuche.present.DelPresent;
import com.example.gouwuche.present.LoginPresent;

import java.util.List;


public class MainActivity extends AppCompatActivity implements LoginPresent.LoginPresentInterface, DelPresent.DelPresentInterface{

    RecyclerView recycler_View;
    RecAdapter recAdapter;
    private RecyclerView recyclerView;
    private TextView total_price;
    private TextView total_num;
    private CheckBox quanxuan;
    List<Bean.DataBean.ListBean> list;
    private LoginPresent loginPresent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        total_price = (TextView) findViewById(R.id.total_price);
        total_num = (TextView) findViewById(R.id.total_num);
        quanxuan = (CheckBox) findViewById(R.id.quanxuan);
        recycler_View = (RecyclerView) findViewById(R.id.recycler_View);

        recycler_View.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));

        recAdapter = new RecAdapter(this);

        loginPresent = new LoginPresent(this);

        loginPresent.get();
        recycler_View.setAdapter(recAdapter);

        recAdapter.setUpdateListener(new RecAdapter.UpdateListener(){
            @Override
            public void setTotal(String total, String num, boolean allCheck) {
                //设置ui的改变
                total_num.setText(""+num+"件商品");//总数量
                total_price.setText("总价 :¥"+total+"");//总价
                if(allCheck){
                    quanxuan.setTag(2);
                    quanxuan.setBackgroundResource(R.drawable.b);
                }else{
                    quanxuan.setTag(1);
                    quanxuan.setBackgroundResource(R.drawable.c);
                }
                quanxuan.setChecked(allCheck);
            }
        });

        quanxuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //调用adapter里面的方法 ,,把当前quanxuan状态传递过去

                int tag = (int) quanxuan.getTag();

                System.out.println("tag = " + tag);


                if(tag==1){

                    quanxuan.setTag(2);

                    quanxuan.setBackgroundResource(R.drawable.b);

                }else{
                    quanxuan.setTag(1);
                    quanxuan.setBackgroundResource(R.drawable.c);

                }
                recAdapter.quanXuan(quanxuan.isChecked());
            }
        });
    }

    @Override
    public void Success(Bean bean) {

        recAdapter.addData(bean);

    }

    @Override
    public void Success(DelBean bean) {

        Toast.makeText(this,bean.getMsg().toString(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void Fail() {

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //调用p层的解除绑定
        loginPresent.detach();
    }
}
主界面

package com.example.gouwuche.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.gouwuche.CustomJiaJian;
import com.example.gouwuche.MainActivity;
import com.example.gouwuche.R;
import com.example.gouwuche.bean.Bean;
import com.example.gouwuche.present.DelPresent;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by D-H-F on 2017/12/11.
 */

public class RecAdapter extends RecyclerView.Adapter<RecAdapter.ViewHolder1>{
    MainActivity mainActivity;
    List<Bean.DataBean.ListBean> list;
     Map<String,String> map = new HashMap<>();
    private DelPresent delPresent;

    public RecAdapter(MainActivity mainActivity) {
        this.mainActivity=mainActivity;
    }
    public void addData(Bean bean) {
        if(list == null){
            list = new ArrayList<>();
        }
        //第一层遍历商家和商品
        for (Bean.DataBean shop : bean.getData()){
            //把商品的id和商品的名称添加到map集合里 ,,为了之后方便调用
            map.put(shop.getSellerid(),shop.getSellerName());
            //第二层遍历里面的商品
            for (int i=0;i<shop.getList().size();i++){
                //添加到list集合里
                list.add(shop.getList().get(i));
            }
        }
        //调用方法 设置显示或隐藏 商铺名
        setFirst(list);
        notifyDataSetChanged();

    }

    private void setFirst(List<Bean.DataBean.ListBean> list) {

        if(list.size()>0){
            //如果是第一条数据就设置isFirst1
            list.get(0).setIsFirst(1);
            //从第二条开始遍历
            for (int i=1;i<list.size();i++){
                //如果和前一个商品是同一家商店的
                if (list.get(i).getSellerid() == list.get(i-1).getSellerid()){
                    //设置成2不显示商铺
                    list.get(i).setIsFirst(2);
                }else{//设置成1显示商铺
                    list.get(i).setIsFirst(1);
                    //如果当前条目选中,把当前的商铺也选中
                    if (list.get(i).isItem_check()==true){
                        list.get(i).setShop_check(list.get(i).isItem_check());
                    }
                }
            }
        }

    }

    @Override
    public ViewHolder1 onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(mainActivity, R.layout.recy_cart_item,null);

        return new ViewHolder1(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder1 holder, final int position) {
        /**
         * 设置商铺的 shop_checkbox和商铺的名字 显示或隐藏
         * */
        if(list.get(position).getIsFirst()==1){
            //显示商家
            holder.shop_checkbox.setVisibility(View.VISIBLE);
            holder.shop_name.setVisibility(View.VISIBLE);
            //设置shop_checkbox的选中状态
            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[] split = list.get(position).getImages().split("\\|");
        //设置商品的图片
        holder.item_face.setImageURI(split[0]);
        //控制商品的item_checkbox,,根据字段改变
        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()+"");
        //调用customjiajian里面的方法设置 加减号中间的数字
        holder.customJiaJian.setEditText(list.get(position).getNum());

        //商铺的shop_checkbox点击事件 ,控制商品的item_checkbox
        holder.shop_checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //先改变数据源中的shop_check
                list.get(position).setShop_check(holder.shop_checkbox.isChecked());

                for (int i=0;i<list.size();i++){
                    //如果是同一家商铺的 都给成相同状态
                    if(list.get(position).getSellerid()==list.get(i).getSellerid()){
                        //当前条目的选中状态 设置成 当前商铺的选中状态
                        list.get(i).setItem_check(holder.shop_checkbox.isChecked());
                    }
                }
                //刷新适配器
                notifyDataSetChanged();
                //调用求和的方法
                sum(list);
            }
        });

        //商品的item_checkbox点击事件,控制商铺的shop_checkbox
        holder.item_checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //先改变数据源中的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++){
                        //如果两个商品是同一家店铺的 并且 这两个商品的item_checkbox选中状态不一样
                        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{
                            //同一家商铺的商品 选中状态都一样,就把商铺shop_checkbox状态改成true
                            list.get(i).setShop_check(true);
                        }
                    }
                }
                //更新适配器
                notifyDataSetChanged();
                //调用求和的方法
                sum(list);
            }
        });

        //删除条目的点击事件
        holder.item_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.remove(position);//移除集合中的当前数据
                //删除完当前的条目 重新判断商铺的显示隐藏
                setFirst(list);
                //调用重新求和
                sum(list);

                delPresent = new DelPresent(mainActivity);

                delPresent.get("100",list.get(position).getPid());

                notifyDataSetChanged();
            }
        });
        //加减号的监听,
        holder.customJiaJian.setCustomListener(new CustomJiaJian.CustomListener() {
            @Override
            public void jiajian(int count) {
                //改变数据源中的数量
                list.get(position).setNum(count);
                notifyDataSetChanged();
                sum(list);
            }

            @Override
            //输入值 求总价
            public void shuRuZhi(int count) {
                list.get(position).setNum(count);
                notifyDataSetChanged();
                sum(list);
            }
        });
    }

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

    private void sum(List<Bean.DataBean.ListBean> list){
        int totalNum = 0;//初始的总价为0
        float totalMoney = 0.0f;
        boolean allCheck = true;
        for (int i=0;i<list.size();i++){
            //把 已经选中的 条目 计算价格
            if (list.get(i).isItem_check()){
                totalNum += list.get(i).getNum();
                totalMoney += list.get(i).getNum() * list.get(i).getPrice();
            }else{
                //如果有个未选中,就标记为false
                allCheck = false;
            }
        }

        //接口回调出去 把总价 总数量 和allcheck 传给view        updateListener.setTotal(totalMoney+"",totalNum+"",allCheck);
    }

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

    class ViewHolder1 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 ViewHolder1(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{

         void setTotal(String total, String num, boolean allCheck);
    }
}
适配器文件

http://blog.csdn.net/thw_m/article/details/78604105这个是网址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值