android 实现简单的一级购物车

**第一步导入依赖,如:
 compile 'com.squareup.okhttp3:okhttp:3.9.0'
 compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'
 compile 'com.google.code.gson:gson:2.8.2'
 compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
 compile 'org.greenrobot:eventbus:3.1.1'
 compile 'com.android.support:recyclerview-v7:24.2.1'
 **别忘了 sync now**
**
**第二步添加权限,如:
"android.permission.INTERNET">

**
**第三步,上代码,最重要**
**net包(Api,HttpUtils,OnNetListener)**
**Api**
public interface Api {
    public static final String url = "http://result.eolinker.com/iYXEPGn4e9c6dafce6e5cdd23287d2bb136ee7e9194d3e9?uri=evaluation";
}

**HttpUtils**
public class HttpUtils {
    private static volatile HttpUtils httpUtils;
    private final OkHttpClient client;

    private HttpUtils() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        client = new OkHttpClient.Builder()
                .addInterceptor(logging)
                .build();
    }

    public static HttpUtils getHttpUtils() {
        if (httpUtils == null) {
            synchronized (HttpUtils.class) {
                if (httpUtils == null) {
                    httpUtils = new HttpUtils();
                }
            }
        }
        return httpUtils;
    }

    public void doGet(String url, Callback callback) {
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(callback);
    }
}

**OnNetListener**
public interface OnNetListener {
    public void onSuccess(T t);
    public void onFailure(Exception e);
}

**bean包(GoodsBean)**
**自己封装,注意封装时可以后加属性哦**

**adapter包(Myadapter)**
**Myadapter**
public class Myadapter extends RecyclerView.Adapter {
    /*上下文*/
    private Context context;
    /*集合*/
    private List list;

    /*有参构造*/
    public Myadapter(Context context, List list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       /*1.加载item布局*/
        View view = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
       /*3.把封装里的数据(datasBean.getType_name)放入优化器( myViewHolder.fx)*/
        final GoosBean.DataBean.DatasBean datasBean = list.get(position);
        final MyViewHolder myViewHolder = (MyViewHolder) holder;
        myViewHolder.fx.setChecked(datasBean.isChecked());
        myViewHolder.myphone.setText(datasBean.getType_name());
        myViewHolder.myplace.setText(datasBean.getMsg());
        myViewHolder.mytime.setText(datasBean.getAdd_time());
        myViewHolder.myprice.setText(datasBean.getPrice() + "");
        myViewHolder.add_num_del.setText(datasBean.getAdd_num_del() + "");
/*要想实现反选效果,在适配器里,给反选设置点击事件,*/
        myViewHolder.fx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*反选打钩*/
                datasBean.setChecked(myViewHolder.fx.isChecked());
                /*结账时候写这两行,具体发送*/
                PriceAndCountEvent compute = compute();
                EventBus.getDefault().post(compute);
                /*如果反选 都 打钩*/
                if(myViewHolder.fx.isChecked()){
                    /*走isAllCbSelected()方法,开始给遍历 判断 反选 状态*/
                    if(isAllCbSelected()){
                         /*changeAllCbState()方法,开始改变 全选 状态并发送*/
                        changeAllCbState(true);
                    }
                }else{
                    changeAllCbState(false);
                }
                notifyDataSetChanged();
            }
        });
        /*直接,加+*/
        myViewHolder.add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*不一样*/
                for (int i = 0; i < list.size(); i++) {
                    GoosBean.DataBean.DatasBean datasBean = list.get(i);
                }
                int add_num_del = datasBean.getAdd_num_del();
                add_num_del++;
                datasBean.setAdd_num_del(add_num_del);
                /*结账*/
                    if(myViewHolder.fx.isChecked()){
                        EventBus.getDefault().post(compute());
                    }
                notifyDataSetChanged();
            }
        });
           /*直接,减-*/
        myViewHolder.del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*不一样*/
                for (int i = 0; i < list.size(); i++) {
                    GoosBean.DataBean.DatasBean datasBean = list.get(i);
                }
                int add_num_del = datasBean.getAdd_num_del();
                if(add_num_del==1){
                return;
                }
                add_num_del--;
                datasBean.setAdd_num_del(add_num_del);
                 /*结账*/
                    if(myViewHolder.fx.isChecked()){
                        EventBus.getDefault().post(compute());
                    }
                notifyDataSetChanged();
            }
        });
        /*删除*/
        myViewHolder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.remove(position);
                EventBus.getDefault().post(compute());
                notifyDataSetChanged();
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
/*若全选,反选都选,allSelect()*/
    public void allSelect(boolean flag) {
        for (int i = 0; i < list.size(); i++) {
            GoosBean.DataBean.DatasBean datasBean = list.get(i);
            datasBean.setChecked(flag);
        }
        /*全选结账直接一句话*/
        EventBus.getDefault().post(compute());

        notifyDataSetChanged();
    }
    private boolean isAllCbSelected() {
        for (int i = 0; i < list.size(); i++) {
            GoosBean.DataBean.DatasBean datasBean = list.get(i);
            if (!datasBean.isChecked()) {
                return false;
            }
        }
        return true;
    }
    /*改变全选状态,并发送*/
    private void changeAllCbState(boolean flag) {
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setChecked(flag);
        EventBus.getDefault().post(messageEvent);
    }
    /*写具体结账逻辑方法*/
    private PriceAndCountEvent compute() {
        int price = 0;
        int count = 0;
        for (int i = 0; i < list.size(); i++) {
            GoosBean.DataBean.DatasBean datasBean = list.get(i);
            if (datasBean.isChecked()) {
                price += datasBean.getPrice() * datasBean.getAdd_num_del();
                count += datasBean.getAdd_num_del();
            }
        }
        PriceAndCountEvent priceAndCountEvent = new PriceAndCountEvent();
        priceAndCountEvent.setPrice(price);
        priceAndCountEvent.setCount(count);
        return priceAndCountEvent;
    }
    /*2.找到布局里的ID*/
    class MyViewHolder extends RecyclerView.ViewHolder {

        private final CheckBox fx;
        private final TextView myphone;
        private final TextView myplace;
        private final TextView mytime;
        private final TextView myprice;
        private final TextView add_num_del;
        private final ImageView add;
        private final ImageView del;
        private final TextView delete;

        public MyViewHolder(View itemView) {
            super(itemView);
            fx = (CheckBox) itemView.findViewById(R.id.fx);
            myphone = (TextView) itemView.findViewById(R.id.myphone);
            myplace = (TextView) itemView.findViewById(R.id.myplace);
            myprice = (TextView) itemView.findViewById(R.id.myprice);
            mytime = (TextView) itemView.findViewById(R.id.mytime);
            add_num_del = (TextView) itemView.findViewById(R.id.add_num_del);
            add = (ImageView) itemView.findViewById(R.id.add);
            del = (ImageView) itemView.findViewById(R.id.del);
            delete = (TextView) itemView.findViewById(R.id.delete);
        }


    }

}

**eventbusevent包(MessageEvent,PriceAndCountEvent)**
**MessageEvent**
public class MessageEvent {
    private boolean checked;

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }
}

**PriceAndCountEvent**
public class PriceAndCountEvent {
    private int price;
    private int count;

    public int getPrice() {
        return price;
    }

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

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}


**model包(IMainModel,MainModel)**
**IMainModel**
public interface IMainModel {
    public void getGoods(OnNetListener onNetListener);
}

*MainModel*
public class MainModel implements IMainModel{
    private Handler handler = new Handler(Looper.getMainLooper());
    @Override
    public void getGoods(final OnNetListener onNetListener) {
        HttpUtils.getHttpUtils().doGet(Api.url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
            String string=response.body().string();
                final GoosBean goosBean = new Gson().fromJson(string, GoosBean.class);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onNetListener.onSuccess(goosBean);
                    }
                });
            }
        });
    }
}
**view(IMainActivity,MainActivity)**
**IMainActivity**
public interface IMainActivity {
    public void showList(List list);
}

**MainActivity**
public class MainActivity extends AppCompatActivity implements IMainActivity{
    private RecyclerView Rv;
    private CheckBox qx;
    private TextView tv_money;
    private TextView tv_num;
    private Myadapter myadapter;
    private MainPresenter mainPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /*注意!!!别忘啦,fx*/
        EventBus.getDefault().register(this);
        mainPresenter = new MainPresenter(this);

        Rv = (RecyclerView) findViewById(R.id.Rv);
        qx = (CheckBox) findViewById(R.id.qx);
        tv_money = (TextView) findViewById(R.id.tv_money);
        tv_num = (TextView) findViewById(R.id.tv_num);

        Rv.setLayoutManager(new LinearLayoutManager(this));
        mainPresenter.getGoods();
/*给全选按钮设置点击事件,状态为ture*/
        qx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*具体勾选与否写在myadapter里*/
                myadapter.allSelect(qx.isChecked());
            }
        });
    }
    @Override
    public void showList(List list) {
        myadapter = new Myadapter(this,list);
        Rv.setAdapter(myadapter);
    }

   /* 接状态,@Subscribe*/
    @Subscribe
    public void onMessageEvent(MessageEvent event){
        qx.setChecked(event.isChecked());

    }
    /*结账*/
    @Subscribe
    public void onMessageEvent(PriceAndCountEvent event) {
        tv_num.setText("结算(" + event.getCount() + ")");
        tv_money.setText(event.getPrice() + "");
    }

**presenter(MainPresenter )**
public class MainPresenter {
    private IMainModel iMainModel;
    private IMainActivity iMainActivity;

    public MainPresenter(IMainActivity iMainActivity) {
        this.iMainActivity = iMainActivity;
        iMainModel = new MainModel();
    }
    public void getGoods(){
        iMainModel.getGoods(new OnNetListener() {
            @Override
            public void onSuccess(GoosBean goosBean) {
                List list = new ArrayList();
                List data = goosBean.getData();
                for (int i = 0; i < data.size(); i++) {
                    List datas = data.get(i).getDatas();
                    list.addAll(datas);
                }
                iMainActivity.showList(list);
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }
}

你可能感兴趣的:(android 实现简单的一级购物车)