implementation 'com.squareup.okhttp3:okhttp:3.9.1'
implementation 'com.google.code.gson:gson:2.8.+'
compile 'com.github.bumptech.glide:glide:3.6.1'
implementation 'com.android.support:recyclerview-v7:26.1.+'
这些是需要用到的依赖 还有别忘了在加 网络权限哦
首先写OKHTTP 封装的时候要实现一个接口
OnFinishListener
/**
* 定义一个接口
*/
public interface OnFinishListener {
void onFailed(String msg);
void onSuccess(Object obj);
}
然后写OKHTTP的封装类
OkHttpUtils
import android.os.Handler;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by rookie on 2018/1/3.
*/
public class OkHttpUtils {
private static OkHttpUtils OK_HTTP_UTILS = null;
//定义一个Handler
private static Handler handler = new Handler();
private OkHttpUtils() {
}
/**
* 得到OkHttpUtils实例对象
*
* @return
*/
public static OkHttpUtils getInstance() {
if (null == OK_HTTP_UTILS) {
synchronized (OkHttpUtils.class) {
if (null == OK_HTTP_UTILS) {
OK_HTTP_UTILS = new OkHttpUtils();
}
}
}
return OK_HTTP_UTILS;
}
/**
* Get请求
*
* @param path http://www.baidu.com?key=value&key=value
* @param onFinishListener
*/
public void doGet(String path,Map<String,String> map,final OnFinishListener onFinishListener) {
//Http:/www.baidu.com?key=ddd&
StringBuffer sb = new StringBuffer();
sb.append(path);
//判断path是否包含一个
if(sb.indexOf("?") != -1){
//判断"?"是否在最后一个
if(sb.indexOf("?") != sb.length() -1){
sb.append("&");
}
}else{
sb.append("?");
}
//遍历map集合中所有请求参数
for (Map.Entry<String, String> entry: map.entrySet()){
sb.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append("&");
}
//判断get请求路径最后是否包含一个"&"
if(sb.lastIndexOf("&") != -1){
sb.deleteCharAt(sb.length() - 1);
}
OkHttpClient okHttpClient = new OkHttpClient.Builder()
//添加应用拦截器
.addInterceptor(new CommonParamsInterceptor())
//.addNetworkInterceptor() //添加网络拦截器
.build();
//构建请求项
Request request = new Request.Builder()
.get()
.url(sb.toString())
.build();
Call call = okHttpClient.newCall(request);
//execute 子线程 enqueue //
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
//请求失败
handler.post(new Runnable() {
@Override
public void run() {
onFinishListener.onFailed(e.getMessage());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//得到服务器的响应结果
final String result = response.body().string();
//请求成功
handler.post(new Runnable() {
@Override
public void run() {
//主线程当中执行
onFinishListener.onSuccess(result);
}
});
}
});
}
}
然后写带有拦截器的类
CommonParamsInterceptor
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* 自定义一个拦截器,每次请求之前携带公共参数
*
* 应用层
*
*/
public class CommonParamsInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
//得到原始的请求对象
Request request = chain.request();
//得到用户所使用的请求方式
String method = request.method();
if("GET".equals(method)){
//url
//原始的请求接口
String oldUrl = request.url().toString();
//拼接成一个新的URL
String newUrl = oldUrl + "&source=android";
//重新构建请求体
request = new Request.Builder()
.url(newUrl)
.build();
}else if("POST".equals(method)){
//得到原始的url
String oldUrl = request.url().toString();
//得到原有的请求参数
FormBody oldBody = (FormBody) request.body();//1 2 3
//新的构建项
FormBody.Builder builder = new FormBody.Builder();
for (int i =0 ; i < oldBody.size(); ++i){
//取出相关请求参数(原有的)
String name = oldBody.name(i);
String value = oldBody.value(i);
//将原始的参数拼装到新的构建体当中
builder.add(name,value);
}
//拼装我们的公共参数
builder.add("source","android");
request = new Request.Builder()
.url(oldUrl)
.post(builder.build())
.build();
}
//重新发送请求
return chain.proceed(request);
}
}
别忘了写一个 储存接口的常亮类
/**
* 常量类
*/
public class Constants {
//请求的服务器主机名
public static final String HOST_NAME = "https://www.zhaoapi.cn";
/**
* 登录请求接口
*/
public static final String LOGIN = HOST_NAME+"/user/login";
/**
* 获取购物车信息
*/
public static final String GET_CARTS = HOST_NAME+"/product/getCarts";
public static final String GET_DingDan = HOST_NAME+"/product/createOrder";
}
然后我们开始写购物车请求数据的MVP
V层的接口
import com.example.gouwu.bean.ShoppCarBean;
import java.util.List;
/**
* Created by HaSee on 2018/1/17.
*/
public interface IMainView {
void onSuccess(List<ShoppCarBean.DataBean> data);
void onFailed(String msg);
}
我们还要写一个 储存接口的常亮类
/**
* 常量类
*/
public class Constants {
//请求的服务器主机名
public static final String HOST_NAME = "https://www.zhaoapi.cn";
/**
* 登录请求接口
*/
public static final String LOGIN = HOST_NAME+"/user/login";
/**
* 获取购物车信息
*/
public static final String GET_CARTS = HOST_NAME+"/product/getCarts";
public static final String GET_DingDan = HOST_NAME+"/product/createOrder";
}
接口写完以后写 V层的Activity 里面包括一些购物车的逻辑 实现了一个 购物车MVP的接口 然后还实现了 购物车逻辑的点击事件 还有 一个创建订单MVP 的接口
MainActivity
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.gouwu.R;
import com.example.gouwu.bean.ShoppCarBean;
import com.example.gouwu.presenter.ChengP;
import com.example.gouwu.presenter.IChengP;
import com.example.gouwu.presenter.IShooppPresenter;
import com.example.gouwu.presenter.ShooppPresenter;
import com.example.gouwu.view.adapter.MyExpandAdapter;
import java.util.List;
public class MainActivity extends AppCompatActivity implements IMainView, MyExpandAdapter.ModifyGoodsItemNumberListener, MyExpandAdapter.CheckGroupItemListener,IChuangView {
/**
* 返回
*/
private TextView mBtnBack;
/**
* 编辑
*/
private TextView mBtnEditor;
private ExpandableListView mExpandList;
/**
* 全选
*/
private CheckBox mBtnCheckAll;
/**
* 合计:¥0.00
*/
private TextView mTvTotalPrice;
/**
* 结算(0)
*/
private TextView mBtnAmount;
private List<ShoppCarBean.DataBean> list;
private MyExpandAdapter adapter;
private IShooppPresenter iShooppPrensenter;
//购买商品的总数量
private int totalNum = 0;
private boolean flag;
//购买商品的总价
private double totalPrice= 0.00; //15.55 15 0.55亿
private IChengP chengP;
private String zongjia;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
//隐藏actionbar
getSupportActionBar().hide();
//去除默认指示器
mExpandList.setGroupIndicator(null);
zongjia+=totalPrice;
chengP = new ChengP(this);
chengP.getCarInfo("4582",zongjia);
iShooppPrensenter= new ShooppPresenter(this);
iShooppPrensenter.getCarInfo("4582");
adapter = new MyExpandAdapter(this);
mExpandList.setAdapter(adapter);
adapter.setModifyGoodsItemNumberListener(this);
//设置商家以及商品是否被选中的监听
adapter.setCheckGroupItemListener(this);
mBtnCheckAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isChoosedAll(((CheckBox)view).isChecked());
//计算商品总价
statisticsPrice();
}
});
//编辑
mBtnEditor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!flag){//编辑 -> 完成\
flag = true;
mBtnEditor.setText("完成");
adapter.showDeleteButton(flag);
}else{
flag = false;
mBtnEditor.setText("编辑");
adapter.showDeleteButton(flag);
}
}
});
}
//二级列表默认展开
private void defaultExpand(){
for (int i = 0; i < adapter.getGroupCount();++i){
mExpandList.expandGroup(i);
}
}
@Override
public void onSuccess(List<ShoppCarBean.DataBean> data) {
this.list=data;
adapter.setList(list);
defaultExpand();
}
@Override
public void onFailed(String msg) {
}
private void initView() {
mBtnBack = (TextView) findViewById(R.id.btnBack);
mBtnEditor = (TextView) findViewById(R.id.btnEditor);
mExpandList = (ExpandableListView) findViewById(R.id.expandList);
mBtnCheckAll = (CheckBox) findViewById(R.id.btnCheckAll);
mTvTotalPrice = (TextView) findViewById(R.id.tvTotalPrice);
mBtnAmount = (TextView) findViewById(R.id.btnAmount);
}
@Override
public void checkGroupItem(int groupPosition, boolean isChecked) {
ShoppCarBean.DataBean dataBean = list.get(groupPosition);
dataBean.setGroupChoosed(isChecked);
//遍历商家里面的商品,将其置为选中状态
for (ShoppCarBean.DataBean.ListBean listBean : dataBean.getList()){
listBean.setChildChoosed(isChecked);
}
//底部结算那个checkbox状态(全选)
if(isCheckAll()){
mBtnCheckAll.setChecked(true);
}else{
mBtnCheckAll.setChecked(false);
}
//刷新适配器
adapter.notifyDataSetChanged();
//计算价格
statisticsPrice();
}
@Override
public void checkChildItem(int groupPosition, int childPosition, boolean isChecked) {
ShoppCarBean.DataBean dataBean = list.get(groupPosition);//商家那一层
List<ShoppCarBean.DataBean.ListBean> listBeans = dataBean.getList();
ShoppCarBean.DataBean.ListBean listBean = listBeans.get(childPosition);
//你点击商家的商品条目将其选中状态记录
listBean.setChildChoosed(isChecked);
//检测商家里面的每一个商品是否被选中,如果被选中,返回boolean
boolean result = isGoodsCheckAll(groupPosition);
if(result){
dataBean.setGroupChoosed(result);
}else{
dataBean.setGroupChoosed(result);
}
//底部结算那个checkbox状态(全选)
if(isCheckAll()){
mBtnCheckAll.setChecked(true);
}else{
mBtnCheckAll.setChecked(false);
}
//刷新适配器
adapter.notifyDataSetChanged();
//计算总价
statisticsPrice();
}
@Override
public void doIncrease(int groupPosition, int childPosition, View view) {
ShoppCarBean.DataBean.ListBean listBean = list.get(groupPosition).getList().get(childPosition);
//取出当前的商品数量
int currentNum = listBean.getNum();
//商品++
currentNum++;
//将商品数量设置javabean上
listBean.setNum(currentNum);
//刷新适配器
adapter.notifyDataSetChanged();
//计算商品价格
statisticsPrice();
}
@Override
public void doDecrease(int groupPosition, int childPosition, View view) {
ShoppCarBean.DataBean.ListBean listBean = list.get(groupPosition).getList().get(childPosition);
//取出当前的商品数量
int currentNum = listBean.getNum();
//直接结束这个方法
if(currentNum == 1){
return;
}
currentNum--;
listBean.setNum(currentNum);
//刷新适配器
adapter.notifyDataSetChanged();
//计算商品价格
statisticsPrice();
}
/**
* 检测某个商家的商品是否都选中,如果都选中的话,商家CheckBox应该是选中状态
* @param groupPosition
* @return
*/
private boolean isGoodsCheckAll(int groupPosition){
List<ShoppCarBean.DataBean.ListBean> listBeans = this.list.get(groupPosition).getList();
//遍历某一个商家的每个商品是否被选中
for (ShoppCarBean.DataBean.ListBean listBean : listBeans){
if(listBean.isChildChoosed()){//是选中状态
continue;
}else{
return false;
}
}
return true;
}
//购物车商品是否全部选中
private boolean isCheckAll(){
for (ShoppCarBean.DataBean dataBean : list){
if(!dataBean.isGroupChoosed()){
return false;
}
}
return true;
}
//全选与反选
private void isChoosedAll(boolean isChecked){
for (ShoppCarBean.DataBean dataBean : list){
dataBean.setGroupChoosed(isChecked);
for (ShoppCarBean.DataBean.ListBean listBean : dataBean.getList()){
listBean.setChildChoosed(isChecked);
}
}
//刷新适配器
adapter.notifyDataSetChanged();
}
/**
* 计算你所选中的商品总价
*/
private void statisticsPrice(){
//初始化值
totalNum = 0;
totalPrice = 0.00;
for (ShoppCarBean.DataBean dataBean : list){
for (ShoppCarBean.DataBean.ListBean listBean : dataBean.getList()){
if(listBean.isChildChoosed()){
totalNum++;
System.out.println("number : "+totalNum);
totalPrice += listBean.getNum()*listBean.getPrice();
}
}
}
//设置文本信息 合计、结算的商品数量
mTvTotalPrice.setText("合计:¥"+totalPrice);
mBtnAmount.setText("结算("+totalNum+")");
}
@Override
public void oncheng(final String cg) {
mBtnAmount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (totalPrice!=0.00) {
if (cg.equals("1")) {
Toast.makeText(MainActivity.this, "创建失败", Toast.LENGTH_SHORT).show();
return;
} else {
Toast.makeText(MainActivity.this, "创建成功", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, DingActivity.class);
startActivity(intent);
}
}else{
Toast.makeText(MainActivity.this, "请选择要购买的商品", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onShibai(String msg) {
}
}
然后P 层的 接口
import com.example.gouwu.bean.ShoppCarBean;
import java.util.List;
/**
* Created by HaSee on 2018/1/17.
*/
public interface IShooppPresenter {
void onSuccess(List<ShoppCarBean.DataBean> data);
void onFailed(String msg);
void onDestory();
void getCarInfo(String uid);
}
然后 P层的类
import com.example.gouwu.bean.ShoppCarBean;
import com.example.gouwu.model.IShoppCarModel;
import com.example.gouwu.model.ShoppCarModel;
import com.example.gouwu.view.IMainView;
import java.util.List;
/**
* Created by HaSee on 2018/1/17.
*/
public class ShooppPresenter implements IShooppPresenter {
private IMainView iMainView;
private IShoppCarModel ishoppCarModel;
public ShooppPresenter(IMainView iMainView) {
this.iMainView = iMainView;
ishoppCarModel = new ShoppCarModel();
}
@Override
public void onSuccess(List<ShoppCarBean.DataBean> data) {
if (iMainView!=null){
iMainView.onSuccess(data);
}
}
@Override
public void onFailed(String msg) {
if (iMainView!=null){
iMainView.onFailed(msg);
}
}
@Override
public void onDestory() {
if (iMainView!=null){
iMainView=null;
}
}
@Override
public void getCarInfo(String uid) {
ishoppCarModel.getCarInfo(uid,this);
}
}
然后M层的接口
package com.example.gouwu.model;
import com.example.gouwu.presenter.IShooppPresenter;
/**
* Created by HaSee on 2018/1/17.
*/
public interface IShoppCarModel {
void getCarInfo(String uid,IShooppPresenter iShooppPrensenter);
}
然后M层的类
import com.example.gouwu.bean.ShoppCarBean;
import com.example.gouwu.presenter.IShooppPresenter;
import com.example.gouwu.utils.Constants;
import com.example.gouwu.utils.OkHttpUtils;
import com.example.gouwu.utils.OnFinishListener;
import com.google.gson.Gson;
import java.util.HashMap;
/**
* Created by HaSee on 2018/1/17.
*/
public class ShoppCarModel implements IShoppCarModel {
@Override
public void getCarInfo(String uid, final IShooppPresenter iShooppPrensenter) {
HashMap<String, String> params = new HashMap<>();
params.put("uid",uid);
OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
okHttpUtils.doGet(Constants.GET_CARTS,params,new OnFinishListener(){
@Override
public void onFailed(String msg) {
iShooppPrensenter.onFailed(msg);
}
@Override
public void onSuccess(Object obj) {
Gson gson = new Gson();
ShoppCarBean shoppCarBean = gson.fromJson(obj.toString(), ShoppCarBean.class);
iShooppPrensenter.onSuccess(shoppCarBean.getData());
}
});
}
}
现在 我们的数据就已经到了V层 然后我们要写 二级列表的 适配器了这里面有点击事件还有 购物车的加减
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.gouwu.R;
import com.example.gouwu.bean.ShoppCarBean;
import java.util.List;
/**
* Created by rookie on 2018/1/9.
*/
public class MyExpandAdapter extends BaseExpandableListAdapter {
private List<ShoppCarBean.DataBean> data;
private Context context;
//商品加减的一个接口变量
private ModifyGoodsItemNumberListener modifyGoodsItemNumberListener;
private CheckGroupItemListener checkGroupItemListener;
//接收是否处于编辑状态的一个boolean值
private boolean isEditor;
public MyExpandAdapter(Context context){
this.context = context;
}
//设置数据
public void setList(List<ShoppCarBean.DataBean> data){
this.data = data;
notifyDataSetChanged();
}
//商家以及商品是否被选中的一个监听
public void setCheckGroupItemListener(CheckGroupItemListener checkGroupItemListener){
this.checkGroupItemListener = checkGroupItemListener;
}
//设置商品的加减监听
public void setModifyGoodsItemNumberListener(ModifyGoodsItemNumberListener modifyGoodsItemNumberListener){
this.modifyGoodsItemNumberListener = modifyGoodsItemNumberListener;
}
//是否显示删除按钮
public void showDeleteButton(boolean isEditor){
this.isEditor = isEditor;
//刷新适配器
notifyDataSetChanged();
}
@Override
public int getGroupCount() {
return data != null ? data.size() : 0;
}
@Override
public int getChildrenCount(int i) {
return data != null && data.get(i).getList() != null ? data.get(i).getList().size() : 0;
}
@Override
public Object getGroup(int groupPosition) {
return data.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return data.get(groupPosition).getList().get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(final int groupPosition, boolean b, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.layout_group_item,parent,false);
}
//查找控件
CheckBox ck_group_choosed = convertView.findViewById(R.id.ck_group_choosed);
//设置商家checkbox复选框的状态
if(data.get(groupPosition).isGroupChoosed()){
ck_group_choosed.setChecked(true);
}else{
ck_group_choosed.setChecked(false);
}
//ck_group_choosed.setChan
ck_group_choosed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkGroupItemListener.checkGroupItem(groupPosition,((CheckBox)view).isChecked());
}
});
//赋值
ck_group_choosed.setText(data.get(groupPosition).getSellerName());
return convertView;
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean b, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.layout_child_item,parent,false);
}
//商品选择
CheckBox ck_child_choosed = convertView.findViewById(R.id.ck_child_choose);
//商品图片
ImageView iv_show_pic = convertView.findViewById(R.id.iv_show_pic);
//商品主标题
TextView tv_commodity_name = convertView.findViewById(R.id.tv_commodity_name);
//商品副标题
TextView tv_commodity_attr = convertView.findViewById(R.id.tv_commodity_attr);
//商品价格
TextView tv_commodity_price = convertView.findViewById(R.id.tv_commodity_price);
//商品数量
TextView tv_commodity_num = convertView.findViewById(R.id.tv_commodity_num);
//商品减
TextView iv_sub = convertView.findViewById(R.id.iv_sub);
//商品加减中的数量变化
final TextView tv_commodity_show_num = convertView.findViewById(R.id.tv_commodity_show_num);
//商品加
TextView iv_add = convertView.findViewById(R.id.iv_add);
//删除按钮
Button btn_commodity_delete = convertView.findViewById(R.id.btn_commodity_delete);
//设置文本信息
tv_commodity_name.setText(data.get(groupPosition).getList().get(childPosition).getTitle());
tv_commodity_attr.setText(data.get(groupPosition).getList().get(childPosition).getSubhead());
tv_commodity_price.setText("¥"+data.get(groupPosition).getList().get(childPosition).getPrice());
tv_commodity_num.setText("x"+data.get(groupPosition).getList().get(childPosition).getNum());
tv_commodity_show_num.setText(data.get(groupPosition).getList().get(childPosition).getNum()+"");
//分割图片地址
String images = data.get(groupPosition).getList().get(childPosition).getImages();
String[] urls = images.split("\\|");
//加载商品图片
Glide.with(context)
.load(urls[0])
.crossFade()
.into(iv_show_pic);
//商品加
iv_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
modifyGoodsItemNumberListener.doIncrease(groupPosition,childPosition,tv_commodity_show_num);
}
});
//设置商品加减的按钮
//商品减
iv_sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
modifyGoodsItemNumberListener.doDecrease(groupPosition,childPosition,tv_commodity_show_num);
}
});
//商品复选框是否被选中
ck_child_choosed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//isChecked false true
checkGroupItemListener.checkChildItem(groupPosition,childPosition,((CheckBox)view).isChecked());
}
});
//处理商品的选中状态
if(data.get(groupPosition).getList().get(childPosition).isChildChoosed()){
ck_child_choosed.setChecked(true);
}else{
ck_child_choosed.setChecked(false);
}
//控制删除按钮的隐藏与显示
if(isEditor){
btn_commodity_delete.setVisibility(View.VISIBLE);
}else{
btn_commodity_delete.setVisibility(View.GONE);
}
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
/**
* 商家的复选框以及商品的复选框是否被选中的接口
*/
/**
* 商家复选框以及商品复选框是否被选中接口
*/
public interface CheckGroupItemListener{
//商家的条目的复选框监听
void checkGroupItem(int groupPosition, boolean isChecked);
//商品的
void checkChildItem(int groupPosition, int childPosition, boolean isChecked);
}
/**
* 商品加减接口
*/
public interface ModifyGoodsItemNumberListener{
//商品添加操作
void doIncrease(int groupPosition, int childPosition, View view);
//商品减少操作
void doDecrease(int groupPosition, int childPosition, View view);
}
}
写完适配器我们的购物车就已经可以点击等操作了 然后这个时候我们要进行订单了 因为我们在购物车MVP 的V层已经进行了判断 如果成立才跳转 这个时候我们的判断数据就需要在写一个MVP来进行传输 下面就是 创建订单的MVP 首先实现一个接口 然后给MainActivity 继承一下
/**
* Created by HaSee on 2018/1/17.
*/
public interface IChuangView {
void oncheng(String cg);
void onShibai(String msg);
}
然后我们 开始做P层的 数据先来实现一个 接口
public interface IChengP {
void onSuccess(String cg);
void onFailed(String msg);
void onDestory();
void getCarInfo(String uid,String price);
}
然后写P层的类
import com.example.gouwu.model.ChengM;
import com.example.gouwu.model.IChengM;
import com.example.gouwu.view.IChuangView;
/**
* Created by HaSee on 2018/1/17.
*/
public class ChengP implements IChengP{
private IChuangView iChuangView;
private IChengM chengM;
public ChengP(IChuangView iChuangView) {
this.iChuangView = iChuangView;
chengM = new ChengM();
}
@Override
public void onSuccess(String cg) {
if (iChuangView!=null){
iChuangView.oncheng(cg);
}
}
@Override
public void onFailed(String msg) {
if (iChuangView!=null){
iChuangView.onShibai(msg);
}
}
@Override
public void onDestory() {
if (iChuangView!=null){
iChuangView=null;
}
}
@Override
public void getCarInfo(String uid,String price) {
chengM.getCarInfo(uid,price,this);
}
}
然后是M层的 接口
public interface IChengM {
void getCarInfo(String uid,String price, final IChengP iChengP);
}
然后是 M层的类
import java.util.HashMap;
/**
* Created by HaSee on 2018/1/17.
*/
public class ChengM implements IChengM {
@Override
public void getCarInfo(String uid,String price, final IChengP iChengP) {
HashMap<String, String> params = new HashMap<>();
params.put("uid",uid);
params.put("price",price);
OkHttpUtils okHttpUtils = OkHttpUtils.getInstance();
okHttpUtils.doGet(Constants.GET_CARTS,params,new OnFinishListener(){
@Override
public void onFailed(String msg) {
iChengP.onFailed(msg);
}
@Override
public void onSuccess(Object obj) {
Gson gson = new Gson();
ChuangJianBean chuangJianBean = gson.fromJson(obj.toString(), ChuangJianBean.class);
String code = chuangJianBean.getCode();
iChengP.onSuccess(code);
}
});
}
}
然后数据就已经到了MainActivity里面 进行判断了 然后条件成立的时候就可以进行跳转 下面我们来写进行跳转的DingActivity 这里面是有一个 RecycleView 的进行订单的展示
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.example.gouwu.R;
import com.example.gouwu.bean.DingBean;
import com.example.gouwu.view.adapter.MyRvAdapter;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class DingActivity extends AppCompatActivity {
private RecyclerView mRv;
private MyRvAdapter adapter;
private LinearLayoutManager linearLayoutManager;
private Handler handler=new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ding);
mRv = (RecyclerView) findViewById(R.id.rv);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRv.setLayoutManager(linearLayoutManager);
OkHttpClient okHttpClient = new OkHttpClient();
Request request=new Request.Builder()
.get()
.url("https://www.zhaoapi.cn/product/getOrders?uid=4582&page=1")
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
String str = response.body().string();
Gson gson = new Gson();
DingBean dingBean = gson.fromJson(str, DingBean.class);
final List<DingBean.DataBean> list = dingBean.getData();
handler.post(new Runnable() {
@Override
public void run() {
//添加分割线
mRv.addItemDecoration(new DividerItemDecoration(DingActivity.this, DividerItemDecoration.VERTICAL));
adapter = new MyRvAdapter(DingActivity.this,list);
mRv.setAdapter(adapter);
}
});
}
}
});
然后这个就是我们上面提到的控件 的适配器
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.example.administrator.gouwucar.R;
import com.example.administrator.gouwucar.bean.DingBean;
import java.util.List;
/**
* Created by HaSee on 2018/1/17.
*/
public class MyRvAdapter extends RecyclerView.Adapter<MyRvAdapter.ViewHoder>{
private Context context;
private List<DingBean.DataBean> list;
public MyRvAdapter(Context context, List<DingBean.DataBean> list) {
this.context = context;
this.list = list;
}
@Override
public MyRvAdapter.ViewHoder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.dingdanitem,parent,false);
ViewHoder viewHoder = new ViewHoder(view);
return viewHoder;
}
@Override
public void onBindViewHolder(MyRvAdapter.ViewHoder holder, final int position) {
holder.text_orderid.setText("订单id:"+list.get(position).getOrderid());
holder.text_price.setText("¥:"+list.get(position).getPrice());
holder.text_createtime.setText("创建时间:"+list.get(position).getCreatetime());
if (list.get(position).getStatus()==0){
holder.text_status.setText("订单状态:待支付");
}else if(list.get(position).getStatus()==1){
holder.text_status.setText("订单状态:已支付");
} else if(list.get(position).getStatus()==2){
holder.text_status.setText("订单状态:已取消");
}
holder.btn_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder=new AlertDialog.Builder(context);
builder.setTitle("订单确认");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
list.get(position).setStatus(1);
notifyDataSetChanged();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
list.get(position).setStatus(2);
notifyDataSetChanged();
}
});
builder.show();
}
});
holder.text_title.setText(list.get(position).getTitle());
}
@Override
public int getItemCount() {
return list!=null?list.size():0;
}
class ViewHoder extends RecyclerView.ViewHolder{
private TextView text_title;
private TextView text_orderid;
private TextView text_price;
private Button btn_submit;
private TextView text_status;
private TextView text_createtime;
public ViewHoder(View itemView) {
super(itemView);
text_title = itemView.findViewById(R.id.text_title);
text_orderid = itemView.findViewById(R.id.text_orderid);
text_price = itemView.findViewById(R.id.text_price);
btn_submit = itemView.findViewById(R.id.btn_submit);
text_status = itemView.findViewById(R.id.text_status);
text_createtime = itemView.findViewById(R.id.text_createtime);
}
}
}
适配器写完以后 我们整个项目一共用到了 三个 GSON 的Class 其中最有用的就是 购物车的
import java.util.List;
public class ShoppCarBean {
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 isGroupChoosed;
public boolean isGroupChoosed() {
return isGroupChoosed;
}
public void setGroupChoosed(boolean groupChoosed) {
isGroupChoosed = groupChoosed;
}
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 isChildChoosed;
public boolean isChildChoosed() {
return isChildChoosed;
}
public void setChildChoosed(boolean childChoosed) {
isChildChoosed = childChoosed;
}
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;
}
}
}
}
ChuangJianBean
public class ChuangJianBean {
/**
* msg : 订单创建成功
* code : 0
*/
private String msg;
private String 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;
}
}
DingBean
import java.util.List;
/**
* Created by Administrator on 2018/4/3 0003.
*/
public class DingBean {
/**
* msg : 请求成功
* code : 0
* data : [{"createtime":"2017-10-19T20:28:43","orderid":20,"price":100,"status":0,"title":"订单标题测试3","uid":71},{"createtime":"2017-10-19T20:44:40","orderid":31,"price":11800,"status":2,"title":"订单标题测试14","uid":71},{"createtime":"2017-10-19T20:44:51","orderid":32,"price":11800,"status":2,"title":"订单标题测试15","uid":71},{"createtime":"2017-10-20T08:02:07","orderid":43,"price":11800,"status":2,"title":"订单标题测试","uid":71},{"createtime":"2017-10-20T08:02:16","orderid":44,"price":11800,"status":2,"title":"订单标题测试","uid":71},{"createtime":"2017-10-22T15:14:39","orderid":890,"price":11800,"status":2,"title":"","uid":71},{"createtime":"2017-11-09T09:17:20","orderid":1446,"price":99.99,"status":1,"title":"订单标题测试","uid":71},{"createtime":"2017-11-09T09:20:58","orderid":1447,"price":567,"status":2,"title":"订单标题测试","uid":71},{"createtime":"2017-11-09T09:20:58","orderid":1448,"price":256.99,"status":2,"title":"订单标题测试","uid":71},{"createtime":"2017-11-09T09:20:58","orderid":1449,"price":399,"status":2,"title":"订单标题测试","uid":71}]
* page : 1
*/
private String msg;
private String code;
private String page;
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 String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
/**
* createtime : 2017-10-19T20:28:43
* orderid : 20
* price : 100.0
* status : 0
* title : 订单标题测试3
* uid : 71
*/
private String createtime;
private int orderid;
private double price;
private int status;
private String title;
private int uid;
public String getCreatetime() {
return createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
public int getOrderid() {
return orderid;
}
public void setOrderid(int orderid) {
this.orderid = orderid;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
}
}