频道栏目
首页 > 程序开发 > 移动开发 > Android > 正文
MVP模式实现Android的简单购物车(世界杯指定投注平台教程)
2018-07-04 13:39:06      个评论    来源:qq_19681347的博客  
收藏   我要投稿

retrofit+rxjava思想,并进行简单的封装.

效果图:

\

\

V层:调用P层方法

P层:连接V层和M层,并在V层关闭视图的时候实现解耦,调用M层方法获取数据返回给V层

M层:获取数据,供P层获取调用

RetrofitUtil工具类:

import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitUtil {
 private static RetrofitUtil instener;
 private OkHttpClient okHttpClient;
 private Retrofit retrofit;
 private RetrofitUtil() {
  HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
  logging.setLevel(HttpLoggingInterceptor.Level.BODY);
  okHttpClient = new OkHttpClient.Builder()
 .connectTimeout(5, TimeUnit.SECONDS)
 .writeTimeout(5, TimeUnit.SECONDS)
 .readTimeout(5, TimeUnit.SECONDS)
 .addInterceptor(logging)
 .build();
  retrofit = new Retrofit.Builder()
 .baseUrl(Api.BASEURL)
 .addConverterFactory(GsonConverterFactory.create())
 .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
 .client(okHttpClient)
 .build();
 }
 public static synchronized RetrofitUtil getInstener() {
  synchronized (RetrofitUtil.class) {
if (instener == null) {
 instener = new RetrofitUtil();
}
  }
  return instener;
 }
 public ApiService getCreate() {
  return retrofit.create(ApiService.class);
 }
}

ApiService:

import com.bwei.jiangbikuan.day0629.model.bean.CatagoryBean;
import com.bwei.jiangbikuan.day0629.model.bean.GetCartsBean;
import com.bwei.jiangbikuan.day0629.model.bean.ProductCatagoryBean;
import io.reactivex.Observable;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface ApiService {
 @GET("product/getCatagory")
 Observable getCatagory();
 @FormUrlEncoded
 @POST("product/getProductCatagory")
 Observable getProductCatagory(@Field("cid") String cid);
 @FormUrlEncoded
 @POST("product/getCarts")
 Observable getCarts(@Field("uid") String uid);
}

分类页面:

V层:

mainactivity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 private FrameLayout myfl;
 private RadioGroup rg;
 private RadioButton rbClass;
 private RadioButton rbShop;
 private FragmentManager fragmentManager;
 private ClassFragment classFragment;
 private ShopFragment shopFragment;
 private int classFragmentcommit;
 private int shopFragmentcommit;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  //初始化控件
  initView();
  //获得fragment管理者
  fragmentManager = getSupportFragmentManager();
  //创建两个模块fragment对象
  classFragment = new ClassFragment();
  shopFragment = new ShopFragment();
  //设置默认显示fragment
  classFragmentcommit = fragmentManager.beginTransaction().replace(R.id.myfl, classFragment).commit();
 }
 private void initView() {
  myfl = (FrameLayout) findViewById(R.id.myfl);
  rg = (RadioGroup) findViewById(R.id.rg);
  rbClass = (RadioButton) findViewById(R.id.rb_class);
  rbShop = (RadioButton) findViewById(R.id.rb_shop);
  rbShop.setOnClickListener(this);
  rbClass.setOnClickListener(this);
 }
 @Override
 public void onClick(View v) {
  switch (v.getId()) {
default:
 break;
case R.id.rb_class:
 if (classFragmentcommit==0){
  fragmentManager.beginTransaction().replace(R.id.myfl, classFragment).commit();
  Toast.makeText(this, "分类创建", Toast.LENGTH_SHORT).show();
 }else{
  fragmentManager.beginTransaction().show(classFragment);
  Toast.makeText(this, "分类显示", Toast.LENGTH_SHORT).show();
 }
 break;
case R.id.rb_shop:
 if (shopFragmentcommit==0) {
  shopFragmentcommit = fragmentManager.beginTransaction().replace(R.id.myfl, shopFragment).commit();
  Toast.makeText(this, "购物车创建", Toast.LENGTH_SHORT).show();
 }else{
  fragmentManager.beginTransaction().show(shopFragment);
  Toast.makeText(this, "购物车显示", Toast.LENGTH_SHORT).show();
 }
 break;
  }
 }
}

ClassFragment :

public class ClassFragment extends Fragment implements CatagoryView, ProductCatagoryView {
 private RecyclerView mClassLeft;
 private ExpandableListView mClassRight;
 private CatagoryPreImp catagoryPreImp;
 private ProductCatagoryperImp productCatagoryperImp;
 @Nullable
 @Override
 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
  View view = inflater.inflate(R.layout.activity_class, null);
  initView(view);
  //绑定
  catagoryPreImp = new CatagoryPreImp(this);
  catagoryPreImp.getCatagory();
  productCatagoryperImp = new ProductCatagoryperImp(this);
  return view;
 }
 @Override
 public void onDestroy() {
  super.onDestroy();
  catagoryPreImp.closeView();
  productCatagoryperImp.closeView();
 }
 private void initView(View view) {
  mClassLeft = (RecyclerView) view.findViewById(R.id.class_left);
  mClassLeft.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
  mClassRight = (ExpandableListView) view.findViewById(R.id.class_right);
 }
 @Override
 public void showData(CatagoryBean catagoryBean) {
  final List list = catagoryBean.getData();
  final LeftAdapter leftAdapter = new LeftAdapter(getContext(), list);
  mClassLeft.setAdapter(leftAdapter);
  leftAdapter.changeBg(0, true);
  productCatagoryperImp.getProductCatagory(list.get(0).getCid() + "");
  leftAdapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(int position) {
 leftAdapter.changeBg(position, true);
 productCatagoryperImp.getProductCatagory(list.get(position).getCid() + "");
}
  });
 }
 @Override
 public void showData(ProductCatagoryBean bean) {
  List data = bean.getData();
  //存放父列表的数据
  List groupList = new ArrayList<>();
  //存放子列表的数据
  List> chlidList = new ArrayList<>();
  //循环添加数据
  for (int i = 0; i < data.size(); i++) {
String name = data.get(i).getName();
List list = data.get(i).getList();
groupList.add(name);
chlidList.add(list);
  }
  //二级列表适配器
  RightAdapter rightAdapter = new RightAdapter(getContext(), groupList, chlidList);
  mClassRight.setAdapter(rightAdapter);
  mClassRight.setGroupIndicator(null);
  mClassRight.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
 return true;
}
  });
  for (int i = 0; i < groupList.size(); i++) {
mClassRight.expandGroup(i);
  }
 }
}

适配器:

左侧列表适配器->LeftAdapter:

public class LeftAdapter extends RecyclerView.Adapter {
 private Context context;
 private List list;
 private LayoutInflater inflater;
 private OnItemClickListener mOnItemClickListener;
 public LeftAdapter(Context context, List list) {
  this.context = context;
  this.list = list;
  inflater = LayoutInflater.from(context);
 }
 public void setOnItemClickListener(OnItemClickListener listener) {
  this.mOnItemClickListener = listener;
 }
 @NonNull
 @Override
 public LeftViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
  View view = inflater.inflate(R.layout.class_left_item, null);
  LeftViewHolder leftViewHolder = new LeftViewHolder(view);
  return leftViewHolder;
 }
 @Override
 public void onBindViewHolder(@NonNull LeftViewHolder holder, final int position) {
  CatagoryBean.DataBean dataBean = list.get(position);
  holder.leftText.setText(dataBean.getName());
  if (dataBean.isChecked()) {
holder.leftText.setTextColor(Color.RED);
holder.itemView.setBackgroundColor(0xFF66CCFF);
  } else {
holder.leftText.setTextColor(Color.BLACK);
holder.itemView.setBackgroundColor(Color.WHITE);
  }
  holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
 if (mOnItemClickListener != null) {
  mOnItemClickListener.onItemClick(position);
 }
}
  });
 }
 @Override
 public int getItemCount() {
  return list.size();
 }
 class LeftViewHolder extends RecyclerView.ViewHolder {
  private final TextView leftText;
  public LeftViewHolder(View itemView) {
super(itemView);
leftText = (TextView) itemView.findViewById(R.id.left_text);
  }
 }
 //选中改变字体颜色和背景颜色
 public void changeBg(int position, boolean flag) {
  //还原所有的原本颜色
  for (int i = 0; i < list.size(); i++) {
list.get(i).setChecked(false);
  }
  //得到你所选择的对象
  CatagoryBean.DataBean dataBean = list.get(position);
  dataBean.setChecked(flag);
  //刷新页面
  notifyDataSetChanged();
 }
}

右侧列表适配器->RightAdapter:

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

import com.example.R;
import com.example.model.bean.ProductCatagoryBean;
import java.util.List;
public class RightAdapter extends BaseExpandableListAdapter {
 private Context context;
 private List groupList;
 private List> chlidList;
 public RightAdapter(Context context, List groupList, List> chlidList) {
  this.context = context;
  this.groupList = groupList;
  this.chlidList = chlidList;
 }
 @Override
 public int getGroupCount() {
  return groupList.size();
 }
 @Override
 public int getChildrenCount(int groupPosition) {
  return 1;
 }
 @Override
 public Object getGroup(int groupPosition) {
  return groupList.get(groupPosition);
 }
 @Override
 public Object getChild(int groupPosition, int childPosition) {
  return chlidList.get(groupPosition).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(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
  GroupViewHolder groupViewHolder;
  if (convertView == null) {
groupViewHolder = new GroupViewHolder();
convertView = View.inflate(context, R.layout.elv_group_item, null);
groupViewHolder.groupText = convertView.findViewById(R.id.group_text);
convertView.setTag(groupViewHolder);
  } else {
groupViewHolder = (GroupViewHolder) convertView.getTag();
  }
  String name = groupList.get(groupPosition);
  groupViewHolder.groupText.setText(name);
  return convertView;
 }
 @Override
 public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
  ChildViewHolder childViewHolder;
  if (convertView == null) {
childViewHolder = new ChildViewHolder();
convertView = View.inflate(context, R.layout.elv_child_item, null);
childViewHolder.child_rv = convertView.findViewById(R.id.child_rv);
convertView.setTag(childViewHolder);
  } else {
childViewHolder = (ChildViewHolder) convertView.getTag();
  }
  List listBeans = chlidList.get(groupPosition);
  childViewHolder.child_rv.setLayoutManager(new GridLayoutManager(context, 3, LinearLayoutManager.VERTICAL, false));
  //recycleView的适配器
  ChildRvAdapter childRvAdapter = new ChildRvAdapter(context, listBeans);
  childViewHolder.child_rv.setAdapter(childRvAdapter);
  return convertView;
 }
 @Override
 public boolean isChildSelectable(int groupPosition, int childPosition) {
  return false;
 }
 class GroupViewHolder {
  TextView groupText;
 }
 class ChildViewHolder {
  RecyclerView child_rv;
 }
}

右侧子列表适配器->ChildRvAdapter:

import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.R;
import com.example.model.bean.ProductCatagoryBean;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.List;
public class ChildRvAdapter extends RecyclerView.Adapter {
 private Context context;
 private List listBeans;
 private LayoutInflater inflater;
 public ChildRvAdapter(Context context, List listBeans) {
  this.context = context;
  this.listBeans = listBeans;
  inflater = LayoutInflater.from(context);
 }
 @NonNull
 @Override
 public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
  View view = inflater.inflate(R.layout.elv_child_rv_item, null);
  ViewHolder viewHolder = new ViewHolder(view);
  return viewHolder;
 }
 @Override
 public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
  ProductCatagoryBean.DataBean.ListBean listBean = listBeans.get(position);
  holder.rvImage.setImageURI(Uri.parse(listBean.getIcon()));
  holder.rvText.setText(listBean.getName());
 }
 @Override
 public int getItemCount() {
  return listBeans.size();
 }
 class ViewHolder extends RecyclerView.ViewHolder {
  private final SimpleDraweeView rvImage;
  private final TextView rvText;
  public ViewHolder(View itemView) {
super(itemView);
rvImage = (SimpleDraweeView) itemView.findViewById(R.id.child_rv_img);
rvText = (TextView) itemView.findViewById(R.id.child_rv_text);
  }
 }
}

P层:

CatagoryPreImp:

public class CatagoryPreImp implements ICatagory {
 private CatagoryView catagoryView;
 private CatagoryImp catagoryImp;
 public CatagoryPreImp(CatagoryView catagoryView) {
  //把V层作为参数传进来,实例化M层,实现连接V层和M层
  this.catagoryView = catagoryView;
  catagoryImp = new CatagoryImp();
 }
 @Override
 public void getCatagory() {
  //调用M层方法,获取数据
  catagoryImp.getCatagory(new CatagoryModel.OnCatagoryListener() {
@Override
public void onCatagoryListener(CatagoryBean catagoryBean) {
 catagoryView.showData(catagoryBean);
}
  });
 }
 //解耦
 public void closeView(){
  if(catagoryView != null){
catagoryView = null;
  }
 }
}

ProductCatagoryperImp:

import com.example.model.ProductCatagoryImp;
import com.example.model.bean.ProductCatagoryBean;
import com.example.model.inter.ProductCatagory;
import com.example.presenter.imp.ProductCatagoryper;
import com.example.view.fragment.inter.ProductCatagoryView;

public class ProductCatagoryperImp implements ProductCatagoryper {
 private ProductCatagoryView productCatagoryView;
 private final ProductCatagoryImp productCatagoryImp;
 public ProductCatagoryperImp(ProductCatagoryView productCatagoryView){
  this.productCatagoryView = productCatagoryView;
  productCatagoryImp = new ProductCatagoryImp();
 }
 @Override
 public void getProductCatagory(String cid) {
  productCatagoryImp.showData(cid, new ProductCatagory.ProductCatagoryListener() {
@Override
public void OnProductCatagoryBean(ProductCatagoryBean productCatagoryBean) {
 productCatagoryView.showData(productCatagoryBean);
}
  });
 }
 //解耦
 public void closeView(){
  if(productCatagoryView != null){
productCatagoryView = null;
  }
 }
}

接口:

ICatagory:

public interface ICatagory {
 void getCatagory();
}

ProductCatagoryper:

public interface ProductCatagoryper {
 void getProductCatagory(String cid);
}

M层:

CatagoryImp:

public class CatagoryImp implements CatagoryModel {
 @Override
 public void getCatagory(final OnCatagoryListener catagoryListener) {
  ApiService apiService = RetrofitUtil.getInstener().getCreate();
  apiService.getCatagory()
 .subscribeOn(Schedulers.io())
 .observeOn(AndroidSchedulers.mainThread())
 .subscribe(new Observer() {
  @Override
  public void onSubscribe(Disposable d) {
  }
  @Override
  public void onNext(CatagoryBean catagoryBean) {
catagoryListener.onCatagoryListener(catagoryBean);
  }
  @Override
  public void onError(Throwable e) {
Log.e("JBK", "onError: " + e);
  }
  @Override
  public void onComplete() {
  }
 });
 }
}

ProductCatagoryImp:

import android.util.Log;
import com.example.model.bean.ProductCatagoryBean;
import com.example.model.inter.ProductCatagory;
import com.example.net.RetrofitUtil;
import com.example.net.api.ApiService;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ProductCatagoryImp implements ProductCatagory {
 @Override
 public void showData(String cid, final ProductCatagoryListener productCatagoryListener) {
  ApiService apiService = RetrofitUtil.getInstener().getCreate();
  apiService.getProductCatagory(cid)
 .subscribeOn(Schedulers.io())
 .observeOn(AndroidSchedulers.mainThread())
 .subscribe(new Observer() {
  @Override
  public void onSubscribe(Disposable d) {
  }
  @Override
  public void onNext(ProductCatagoryBean productCatagoryBean) {
productCatagoryListener.OnProductCatagoryBean(productCatagoryBean);
  }
  @Override
  public void onError(Throwable e) {
Log.e("JBK", "onError: " + e);
  }
  @Override
  public void onComplete() {
  }
 });
 }
}

接口:

CatagoryModel:

public interface CatagoryModel {
 void getCatagory(OnCatagoryListener catagoryListener);
 interface OnCatagoryListener{
  void onCatagoryListener(CatagoryBean catagoryBean);
 }
}

ProductCatagory:

import com.example.model.bean.ProductCatagoryBean;

public interface ProductCatagory {
 void showData(String cid,ProductCatagoryListener productCatagoryListener);
 interface ProductCatagoryListener {
  void OnProductCatagoryBean(ProductCatagoryBean productCatagoryBean);
 }
}

购物车页面:

V层:

ShopFragment:

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.R;
import com.example.adapter.ShopElvAdapter;
import com.example.model.bean.GetCartsBean;
import com.example.model.bean.MessageEvent.MessageEvent;
import com.example.model.bean.MessageEvent.PriceAndNumEvent;
import com.example.model.bean.SellectBean;
import com.example.presenter.inter.GetCartsPreImp;
import com.example.view.fragment.inter.GetCartsView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.util.ArrayList;
import java.util.List;
public class ShopFragment extends Fragment implements View.OnClickListener, GetCartsView {
 private GetCartsPreImp getCartsPreImp;
 private View view;
 private ExpandableListView mElv;
 /**
  * 全选
  */
 private CheckBox mCbAll;
 /**
  * 合计:
  */
 private TextView mTvMoney;
 /**
  * 去结算:
  */
 private TextView mTvTotal;
 private ShopElvAdapter shopElvAdapter;
 @Nullable
 @Override
 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
  View view = inflater.inflate(R.layout.activity_shop, null);
  //调取P层.获取数据
  getCartsPreImp = new GetCartsPreImp(this);
  getCartsPreImp.showData("13180");
  //初始化控件
  initView(view);
  //注册EventBus
  EventBus.getDefault().register(this);
  return view;
 }
 //解耦
 @Override
 public void onDestroy() {
  super.onDestroy();
  EventBus.getDefault().unregister(this);
  getCartsPreImp.closeView();
 }
 private void initView(View view) {
  mElv = (ExpandableListView) view.findViewById(R.id.elv);
  mCbAll = (CheckBox) view.findViewById(R.id.cbAll);
  mCbAll.setOnClickListener(this);
  mTvMoney = (TextView) view.findViewById(R.id.tvMoney);
  mTvTotal = (TextView) view.findViewById(R.id.tvTotal);
 }
 @Override
 public void onClick(View v) {
  switch (v.getId()) {
default:
 break;
case R.id.cbAll:
 shopElvAdapter.changeAllState(mCbAll.isChecked());
 break;
  }
 }
 @Override
 public void showData(GetCartsBean getCartsBean) {
  //存放商家的集合
  List groupList = new ArrayList<>();
  //存放商品的集合
  List> childList = new ArrayList();
  List data = getCartsBean.getData();
  for (int i = 0; i < data.size(); i++) {
GetCartsBean.DataBean dataBean = data.get(i);
String sellerName = dataBean.getSellerName();
boolean checked = dataBean.isChecked();
String sellerid = dataBean.getSellerid();
List list = dataBean.getList();
//存放数据
SellectBean sellectBean = new SellectBean();
sellectBean.setSellerid(sellerid);
sellectBean.setSellerName(sellerName);
sellectBean.setChecked(checked);
//向List添加数据
groupList.add(sellectBean);
childList.add(list);
  }
  //适配器
  shopElvAdapter = new ShopElvAdapter(getContext(), groupList, childList);
  mElv.setAdapter(shopElvAdapter);
  for (int i = 0; i < data.size(); i++) {
mElv.expandGroup(i);
  }
 }
 @Subscribe
 public void onMessage(PriceAndNumEvent priceAndNumEvent) {
  mTvMoney.setText("合计:" + priceAndNumEvent.getPrice());
  mTvTotal.setText("去结算:" + priceAndNumEvent.getNum());
 }
 @Subscribe
 public void onMessageFlag(MessageEvent event) {
  boolean flag = event.isFlag();
  mCbAll.setChecked(flag);
 }
}

接口:

GetCartsView:

import com.example.model.bean.GetCartsBean;
/**
 * Created by Administrator on 2018/7/2.
 */
public interface GetCartsView {
 void showData(GetCartsBean getCartsBean);
}

P层:

GetCartsPreImp:

import com.example.model.GetCartsImp;
import com.example.model.bean.GetCartsBean;
import com.example.model.inter.GetCarts;
import com.example.presenter.imp.GetCartsPre;
import com.example.view.fragment.inter.GetCartsView;
public class GetCartsPreImp implements GetCartsPre {
 private GetCartsView getCartsView;
 private final GetCartsImp getCartsImp;
 public GetCartsPreImp(GetCartsView getCartsView){
  this.getCartsView = getCartsView;
  getCartsImp = new GetCartsImp();
 }
 @Override
 public void showData(String uid) {
  getCartsImp.showData(uid, new GetCarts.GetCartsListener() {
@Override
public void onGetCartsListener(GetCartsBean getCartsBean) {
 getCartsView.showData(getCartsBean);
}
  });
 }
 public void closeView() {
  if (getCartsView != null) {
getCartsView = null;
  }
 }
}

接口:

GetCartsPre:

public interface GetCartsPre {
 void showData(String uid);
}

M层:

GetCartsImp:

import android.util.Log;
import com.example.model.bean.GetCartsBean;
import com.example.model.inter.GetCarts;
import com.example.net.RetrofitUtil;
import com.example.net.api.ApiService;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class GetCartsImp implements GetCarts {
 @Override
 public void showData(String uid, final GetCartsListener getCartsListener) {
  ApiService apiService = RetrofitUtil.getInstener().getCreate();
  apiService.getCarts(uid)
 .subscribeOn(Schedulers.io())
 .observeOn(AndroidSchedulers.mainThread())
 .subscribe(new Observer() {
  @Override
  public void onSubscribe(Disposable d) {
  }
  @Override
  public void onNext(GetCartsBean getCartsBean) {
getCartsListener.onGetCartsListener(getCartsBean);
  }
  @Override
  public void onError(Throwable e) {
Log.e("JBK", "onError: " + e);
  }
  @Override
  public void onComplete() {
  }
 });
 }
}

接口:

GetCarts:

import com.example.model.bean.GetCartsBean;
public interface GetCarts {
 void showData(String uid,GetCartsListener getCartsListener);
 interface GetCartsListener{
  void onGetCartsListener(GetCartsBean getCartsBean);
 }
}

适配器:

ShopElvAdapter:

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import com.example.R;
import com.example.model.bean.GetCartsBean;
import com.example.model.bean.MessageEvent.MessageEvent;
import com.example.model.bean.MessageEvent.PriceAndNumEvent;
import com.example.model.bean.SellectBean;
import com.example.view.fragment.AddSubView;
import com.facebook.drawee.view.SimpleDraweeView;
import org.greenrobot.eventbus.EventBus;
import java.util.List;
public class ShopElvAdapter extends BaseExpandableListAdapter {
 private Context context;
 private List groupList;
 private List> childList;
 public ShopElvAdapter(Context context, List groupList, List> childList) {
  this.context = context;
  this.groupList = groupList;
  this.childList = childList;
 }
 @Override
 public int getGroupCount() {
  return groupList.size();
 }
 @Override
 public int getChildrenCount(int groupPosition) {
  return childList.get(groupPosition).size();
 }
 @Override
 public Object getGroup(int groupPosition) {
  return groupList.get(groupPosition);
 }
 @Override
 public Object getChild(int groupPosition, int childPosition) {
  return childList.get(groupPosition).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 isExpanded, View convertView, ViewGroup parent) {
  final GroupViewHolder groupViewHolder;
  if (convertView == null) {
groupViewHolder = new GroupViewHolder();
convertView = View.inflate(context, R.layout.shop_elv_group, null);
groupViewHolder.shop_group_cb = convertView.findViewById(R.id.shop_group_cb);
convertView.setTag(groupViewHolder);
  } else {
groupViewHolder = (GroupViewHolder) convertView.getTag();
  }
  final SellectBean sellectBean = groupList.get(groupPosition);
  groupViewHolder.shop_group_cb.setText(sellectBean.getSellerName());
  groupViewHolder.shop_group_cb.setChecked(sellectBean.isChecked());
  groupViewHolder.shop_group_cb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
 //判断一级列表复选框的状态,设置为true或者false
 sellectBean.setChecked(groupViewHolder.shop_group_cb.isChecked());
 //改变二级复选框的状态
 checkedGroup(groupPosition, groupViewHolder.shop_group_cb.isChecked());
 //计算价格和数量
 PriceAndNumEvent priceAndNumEvent = computeMoneyAndNum();
 EventBus.getDefault().post(priceAndNumEvent);
 //判断一级列表的状态是否全部选中
 changeAllStart(isAllGroupSelect());
 //刷新
 notifyDataSetChanged();
}
  });
  return convertView;
 }
 @Override
 public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
  final ChildViewHolder childViewHolder;
  if (convertView == null) {
childViewHolder = new ChildViewHolder();
convertView = View.inflate(context, R.layout.shop_elv_child, null);
childViewHolder.shop_child_cb = convertView.findViewById(R.id.shop_child_cb);
childViewHolder.shop_child_img = convertView.findViewById(R.id.shop_child_img);
childViewHolder.shop_child_title = convertView.findViewById(R.id.shop_child_title);
childViewHolder.shop_child_price = convertView.findViewById(R.id.shop_child_price);
childViewHolder.addSubView = convertView.findViewById(R.id.addSubView);
convertView.setTag(childViewHolder);
  } else {
childViewHolder = (ChildViewHolder) convertView.getTag();
  }
  final GetCartsBean.DataBean.ListBean listBean = childList.get(groupPosition).get(childPosition);
  String[] split = listBean.getImages().split("\\|");
  childViewHolder.shop_child_cb.setChecked(listBean.isChecked());
  childViewHolder.shop_child_img.setImageURI(split[0]);
  childViewHolder.shop_child_title.setText(listBean.getTitle());
  childViewHolder.shop_child_title.setTextColor(Color.BLACK);
  childViewHolder.shop_child_price.setText("¥:" + listBean.getPrice() + "");
  childViewHolder.shop_child_price.setTextColor(Color.RED);
  childViewHolder.addSubView.setNum(listBean.getNum());
  //添加点击事件
  //checkBox的点击事件
  childViewHolder.shop_child_cb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
 //设置该条目中的CheckBox的状态
 listBean.setChecked(childViewHolder.shop_child_cb.isChecked());
 //计算价格
 PriceAndNumEvent priceAndNumEvent = computeMoneyAndNum();
 EventBus.getDefault().post(priceAndNumEvent);
 //判断当前checkbox的选择状态
 if (childViewHolder.shop_child_cb.isChecked()) {
  //全部选中
  if (isAllChlidSelected(groupPosition)) {
//改变一级列表的状态
changeGroupState(groupPosition, true);
//改变全选状态
changeAllStart(isAllGroupSelect());
  }
 } else {
  //如果没有全部选中,一级列表的checkbox不选中
  changeGroupState(groupPosition, false);
  changeAllStart(isAllGroupSelect());
 }
 notifyDataSetChanged();
}
  });
  //加减号
  childViewHolder.addSubView.setOnAddOrSubClickListener(new AddSubView.OnAddOrSubClickListener() {
@Override
public void onClickAdd(View view) {
 int num = listBean.getNum();
 num++;
 childViewHolder.addSubView.setNum(num);
 listBean.setNum(num);
 if (childViewHolder.shop_child_cb.isChecked()) {
  PriceAndNumEvent priceAndNumEvent = computeMoneyAndNum();
  EventBus.getDefault().post(priceAndNumEvent);
 }
}
@Override
public void onClickSub(View view) {
 int num = listBean.getNum();
 if (num == 1) {
  return;
 }
 num--;
 childViewHolder.addSubView.setNum(num);
 listBean.setNum(num);
 if (childViewHolder.shop_child_cb.isChecked()) {
  PriceAndNumEvent priceAndNumEvent = computeMoneyAndNum();
  EventBus.getDefault().post(priceAndNumEvent);
 }
}
  });
  return convertView;
 }
 @Override
 public boolean isChildSelectable(int groupPosition, int childPosition) {
  return false;
 }
 class GroupViewHolder {
  CheckBox shop_group_cb;
 }
 class ChildViewHolder {
  CheckBox shop_child_cb;
  SimpleDraweeView shop_child_img;
  TextView shop_child_title;
  TextView shop_child_price;
  AddSubView addSubView;
 }
 //改变一级列表的checkbox的状态
 private void changeGroupState(int i, boolean flag) {
  SellectBean sellectBean = groupList.get(i);
  sellectBean.setChecked(flag);
 }
 //改变二级列表的checkbox的状态
 private void changeChlidState(int i, boolean flag) {
  List listBeans = childList.get(i);
  for (int j = 0; j < listBeans.size(); j++) {
GetCartsBean.DataBean.ListBean listBean = listBeans.get(j);
listBean.setChecked(flag);
  }
 }
 //判断二级列表是否全部选中
 private boolean isAllChlidSelected(int i) {
  List listBeans = childList.get(i);
  for (int j = 0; j < listBeans.size(); j++) {
GetCartsBean.DataBean.ListBean listBean = listBeans.get(j);
if (!listBean.isChecked()) {
 return false;
}
  }
  return true;
 }
 //一级列表选中后,将对应的子类表选中
 private void checkedGroup(int position, boolean flag) {
  for (int i = 0; i < childList.get(position).size(); i++) {
GetCartsBean.DataBean.ListBean listBean = childList.get(position).get(i);
listBean.setChecked(flag);
  }
 }
 //判断一级类表是否全部选中
 public boolean isAllGroupSelect() {
  for (int i = 0; i < childList.size(); i++) {
SellectBean sellectBean = groupList.get(i);
if (!sellectBean.isChecked()) {
 return false;
}
  }
  return true;
 }
 //改变全选的状态
 private void changeAllStart(boolean flag) {
  //EventBus传值
  MessageEvent messageEvent = new MessageEvent();
  messageEvent.setFlag(flag);
  EventBus.getDefault().post(messageEvent);
 }
 //计算选中商品的价格和数量
 private PriceAndNumEvent computeMoneyAndNum() {
  double sumPrice = 0;
  int sumNum = 0;
  for (int i = 0; i < groupList.size(); i++) {
List listBeans = childList.get(i);
for (int j = 0; j < listBeans.size(); j++) {
 GetCartsBean.DataBean.ListBean listBean = listBeans.get(j);
 //判断是否选中
 if (listBean.isChecked()) {
  sumNum += listBean.getNum();
  sumPrice += listBean.getNum() * listBean.getPrice();
 }
}
  }
  PriceAndNumEvent priceAndNumEvent = new PriceAndNumEvent();
  priceAndNumEvent.setPrice(sumPrice);
  priceAndNumEvent.setNum(sumNum);
  return priceAndNumEvent;
 }
 //设置全选,全不选
 public void changeAllState(boolean flag) {
  for (int i = 0; i < childList.size(); i++) {
changeGroupState(i, flag);
changeChlidState(i, flag);
  }
  //计算价格
  PriceAndNumEvent priceAndNumEvent = computeMoneyAndNum();
  EventBus.getDefault().post(priceAndNumEvent);
  notifyDataSetChanged();
 }
}

ChildRvAdapter:

import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.R;
import com.example.model.bean.ProductCatagoryBean;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.List;
public class ChildRvAdapter extends RecyclerView.Adapter {
 private Context context;
 private List listBeans;
 private LayoutInflater inflater;
 public ChildRvAdapter(Context context, List listBeans) {
  this.context = context;
  this.listBeans = listBeans;
  inflater = LayoutInflater.from(context);
 }
 @NonNull
 @Override
 public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
  View view = inflater.inflate(R.layout.elv_child_rv_item, null);
  ViewHolder viewHolder = new ViewHolder(view);
  return viewHolder;
 }
 @Override
 public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
  ProductCatagoryBean.DataBean.ListBean listBean = listBeans.get(position);
  holder.rvImage.setImageURI(Uri.parse(listBean.getIcon()));
  holder.rvText.setText(listBean.getName());
 }
 @Override
 public int getItemCount() {
  return listBeans.size();
 }
 class ViewHolder extends RecyclerView.ViewHolder {
  private final SimpleDraweeView rvImage;
  private final TextView rvText;
  public ViewHolder(View itemView) {
super(itemView);
rvImage = (SimpleDraweeView) itemView.findViewById(R.id.child_rv_img);
rvText = (TextView) itemView.findViewById(R.id.child_rv_text);
  }
 }
}

EventBus管理:

MessageEvent:

public class MessageEvent {
 private boolean flag;
 public boolean isFlag() {
  return flag;
 }
 public void setFlag(boolean flag) {
  this.flag = flag;
 }
}

PriceAndNumEvent:

public class PriceAndNumEvent {
 private double price;
 private int num;
 public double getPrice() {
  return price;
 }
 public void setPrice(double price) {
  this.price = price;
 }
 public int getNum() {
  return num;
 }
 public void setNum(int num) {
  this.num = num;
 }
}
点击复制链接 与好友分享!回本站首页
上一篇:Android多点触控RadioGroup结合Fragment实现底部Tab
下一篇:介绍一下Android系统架构和应用程序的基本概念
相关文章
图文推荐

关于我们 | 联系我们 | 服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑--致力于做实用的IT技术学习网站

世界杯投注官网