Cart示例

这是一个关于购物车功能的Android应用实现,包括model层、工具类、接口定义、 presenter层、activity、自定义布局、适配器及数据计算。model层负责请求数据,使用OkHttp3获取并解析JSON数据。commonUtils工具类包含UI线程方法和其他实用方法。接口ICartPresenter定义了数据获取的回调,CartPresenter实现了该接口,处理数据回调到view层。在MainActivity中实现了view接口,处理数据并展示。适配器用于渲染购物车列表,实现商品的加减、选择等功能,并根据选择状态更新数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//model层   请求数据;

package wuweixiong.bwie.com.gouwucheexam2.model;

import android.util.Log;

import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import wuweixiong.bwie.com.gouwucheexam2.model.bean.CartBean;
import wuweixiong.bwie.com.gouwucheexam2.presenter.interfac.ICartPresenter;
import wuweixiong.bwie.com.gouwucheexam2.util.CommonUtils;
import wuweixiong.bwie.com.gouwucheexam2.util.OkHttp3Util;

/**
* Created by on 2017/12/12.
* 购物车的model层
*/
public class CartModel {
private ICartPresenter iCartPresenter;

public CartModel(ICartPresenter iCartPresenter) {
this.iCartPresenter = iCartPresenter;
}

public void getCartData(final String cartUrl) {
//获取数据
OkHttp3Util.doGet(cartUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(cartUrl,e.getLocalizedMessage());
}

@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
final String json = response.body().string();
//把数据放到一个工具类中  (有线程)
CommonUtils.runOnUIThread(new Runnable() {
@Override
public void run() {
//gson解析得到数据
Gson gson = new Gson();
CartBean cartBean = gson.fromJson(json, CartBean.class);
//返回数据到主线程
iCartPresenter.getSuccessCartJson(cartBean);
}
});

}
}
});

}
}

//commonUtils工具类

//可以只写最后一个线程方法

package wuweixiong.bwie.com.gouwucheexam2.util;

/**
* Created by Dash
*/
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.view.View;

import wuweixiong.bwie.com.gouwucheexam2.application.DashApplication;

/**
* Created by
*/
public class CommonUtils {
public static final String TAG = "Dash";//sp文件的xml名称
private static SharedPreferences sharedPreferences;

/**
* DashApplication.getAppContext()可以使用,但是会使用系统默认的主题样式,如果你自定义了某些样式可能不会被使用
* @param layoutId
* @return
*/
public static View inflate(int layoutId) {
View view = View.inflate(DashApplication.getAppContext(), layoutId, null);
return view;
}

/**
* dip---px
*
* @param dip 设备独立像素device independent px....1dp = 3px 1dp = 2px 1dp = 1.5px
* @return
*/
public static int dip2px(int dip) {
//获取像素密度
float density = DashApplication.getAppContext().getResources().getDisplayMetrics().density;
//
int px = (int) (dip * density + 0.5f);//100.6
return px;

}

/**
* px-dip
*
* @param px
* @return
*/
public static int px2dip(int px) {
//获取像素密度
float density = DashApplication.getAppContext().getResources().getDisplayMetrics().density;
//
int dip = (int) (px / density + 0.5f);
return dip;

}

/**
* 获取资源中的字符串
* @param stringId
* @return
*/
public static String getString(int stringId) {
return DashApplication.getAppContext().getResources().getString(stringId);
}

public static Drawable getDrawable(int did) {
return DashApplication.getAppContext().getResources().getDrawable(did);
}

public static int getDimens(int id) {
return DashApplication.getAppContext().getResources().getDimensionPixelSize(id);
}

/**
* sp存入字符串类型的值
* @param flag
* @param str
*/
public static void saveSp(String flag, String str) {
if (sharedPreferences == null) {
sharedPreferences = DashApplication.getAppContext().getSharedPreferences(TAG, DashApplication.getAppContext().MODE_PRIVATE);
}
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(flag, str);
edit.commit();
}

public static String getSp(String flag) {
if (sharedPreferences == null) {
sharedPreferences = DashApplication.getAppContext().getSharedPreferences(TAG, DashApplication.getAppContext().MODE_PRIVATE);
}
return sharedPreferences.getString(flag, "");
}

public static boolean getBoolean(String tag) {
if (sharedPreferences == null) {
sharedPreferences = DashApplication.getAppContext().getSharedPreferences(TAG, DashApplication.getAppContext().MODE_PRIVATE);
}
return sharedPreferences.getBoolean(tag, false);
}

public static void putBoolean(String tag, boolean content) {
if (sharedPreferences == null) {
sharedPreferences = DashApplication.getAppContext().getSharedPreferences(TAG, DashApplication.getAppContext().MODE_PRIVATE);
}
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putBoolean(tag, content);
edit.commit();
}

/**
* 清除sp数据
* @param tag
*/
public static void clearSp(String tag) {
if (sharedPreferences == null) {
sharedPreferences = DashApplication.getAppContext().getSharedPreferences(TAG, DashApplication.getAppContext().MODE_PRIVATE);
}
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.remove(tag);
edit.commit();
}

/**
* 自己写的运行在主线程的方法
* 如果是主线程,执行任务,否则使用handler发送到主线程中去执行
*
*
* @param runable
*/
public static void runOnUIThread(Runnable runable) {
//先判断当前属于子线程还是主线程
if (android.os.Process.myTid() == DashApplication.getMainThreadId()) {
runable.run();
} else {
//子线程
DashApplication.getAppHanler().post(runable);
}
}
}

//P层

//接口ICartPresenter 

public interface ICartPresenter {
void getSuccessCartJson(CartBean cartBean);
}

//实现接口CartPresenter 

public class CartPresenter implements ICartPresenter {

private final CartModel cartModel;
private IMainActivity iMainActivity;

public CartPresenter(IMainActivity iMainActivity) {
this.iMainActivity = iMainActivity;
cartModel = new CartModel(this);
}

public void getCartData(String cartUrl) {
cartModel.getCartData(cartUrl);

}

@Override
public void getSuccessCartJson(CartBean cartBean) {
//回调给view
iMainActivity.getSuccessCartData(cartBean);
}
/**
* 销毁 解决内存泄漏
*/
public void destroy(){
if (iMainActivity != null){
iMainActivity = null;
}
}
}


//application:

public class DashApplication extends Application {

private static Context context;
private static Handler handler;
private static int mainId;
public static boolean isLoginSuccess;//是否已经登录的状态


@Override
public void onCreate() {
super.onCreate();

//关于context----http://blog.youkuaiyun.com/lmj623565791/article/details/40481055
context = getApplicationContext();
//初始化handler
handler = new Handler();
//主线程的id
mainId = Process.myTid();


}

/**
* 对外提供了context
* @return
*/
public static Context getAppContext() {
return context;
}

/**
* 得到全局的handler
* @return
*/
public static Handler getAppHanler() {
return handler;
}

/**
* 获取主线程id
* @return
*/
public static int getMainThreadId() {
return mainId;
}
}

//View层

public interface IMainActivity {
void getSuccessCartData(CartBean cartBean);
}

//Activity实现view接口

public class MainActivity extends AppCompatActivity implements IMainActivity, View.OnClickListener {
private CartExpanableListview expanableListview;
private CartPresenter cartPresenter;
private CheckBox check_all;
private TextView text_total;
private TextView text_buy;
private CartBean cartBean;
private RelativeLayout relative_progress;
private MyAdapter myAdapter;

private LinearLayout linear_bottom;

private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what == 0){
CountPriceBean countPriceBean = (CountPriceBean) msg.obj;
text_total.setText("合计:¥"+countPriceBean.getPriceString());
text_buy.setText("去结算("+countPriceBean.getCount()+")");
}
}
};

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

check_all = findViewById(R.id.check_all);
text_total = findViewById(R.id.text_total);
text_buy = findViewById(R.id.text_buy);
expanableListview = findViewById(R.id.expanable_listview);
relative_progress = findViewById(R.id.relative_progress);
linear_bottom = findViewById(R.id.linear_layout);

//去掉默认的指示器
expanableListview.setGroupIndicator(null);

cartPresenter = new CartPresenter(this);

//1.点击全选:选中/未选中...调用适配器中的方法...myAdapter.setIsCheckAll(true);来设置所有的一级和二级是否选中,计算
check_all.setOnClickListener(this);
text_buy.setOnClickListener(this);
}

@Override
protected void onResume() {
super.onResume();

relative_progress.setVisibility(View.VISIBLE);
//请求数据
cartPresenter.getCartData(ApiUtil.cartUrl);

}



@Override
public void getSuccessCartData(CartBean cartBean) {

relative_progress.setVisibility(View.GONE);
this.cartBean = cartBean;

if (cartBean != null){
//显示下面的
linear_bottom.setVisibility(View.VISIBLE);

//1.根据组中子条目是否选中,,,决定该组是否选中...初始化一下每一组中isGroupCheck这个数据
for (int i = 0;i<cartBean.getData().size();i++){
if (isAllChildInGroupSelected(i)){
//更改i位置 组的选中状态
cartBean.getData().get(i).setGroupChecked(true);
}
}

//2.根据每一个组是否选中的状态,,,初始化全选是否选中
check_all.setChecked(isAllGroupChecked());

//设置适配器
myAdapter = new MyAdapter(MainActivity.this, cartBean,handler,cartPresenter,relative_progress);
expanableListview.setAdapter(myAdapter);



//展开
for (int i= 0;i<cartBean.getData().size();i++){
expanableListview.expandGroup(i);
}

//3.根据子条目是否选中 初始化价格和数量
myAdapter.sendPriceAndCount();

}else {
//隐藏下面的全选.... 等
linear_bottom.setVisibility(View.GONE);
//显示去逛逛,,,添加购物车
Toast.makeText(MainActivity.this,"购物车为空,去逛逛",Toast.LENGTH_SHORT).show();

}


}

/**
* 所有的一级列表是否选中
*/
private boolean isAllGroupChecked() {
for (int i =0;i<cartBean.getData().size();i++){
if (! cartBean.getData().get(i).isGroupChecked()){//代表一级列表有没选中的
return false;
}
}

return true;
}

/**
* 判断当前组里面所有的子条目是否选中
* @param groupPosition
* @return
*/
private boolean isAllChildInGroupSelected(int groupPosition) {
for (int i= 0;i<cartBean.getData().get(groupPosition).getList().size();i++){
//只要有一个没选中就返回false
if (cartBean.getData().get(groupPosition).getList().get(i).getSelected() ==0){
return false;
}
}

return true;
}

@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.check_all:
myAdapter.setAllChildState(check_all.isChecked());

break;
case R.id.text_buy://去结算...试一下创建订单
Toast.makeText(MainActivity.this,"开发中...",Toast.LENGTH_SHORT).show();
final String price = countPriceBean.getPrice();
Map<String, String> params = new HashMap<>();
params.put("uid","2845");
params.put("price", String.valueOf(price));
OkHttp3Util.doPost(ApiUtil.createCartUrl, params, new Callback() {
@Override
public void onFailure(Call call, IOException e) {

}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
final String json = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
// Toast.makeText(MainActivity.this,json,Toast.LENGTH_SHORT).show();
CountPriceBean countPriceBean=new CountPriceBean( price,1);
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
// intent.putExtra("toux",chachebean.getData().get(0).getList().g)
intent.putExtra("order",countPriceBean);
startActivity(intent);
}
});

}
}
});
break;

case R.id.but3://删除按钮

for (int i= 0;i<cartBean.getData().size();i++){
if (cartBean.getData().get(i).isGroupChecked()==true){
for (int j=0;j<cartBean.getData().get(i).getList().size();j++){
if (cartBean.getData().get(i).getList().get(j).getSelected() == 1) {
Log.d("ggg",cartBean.getData().get(i).getList().get(j).getPid()+"");
OkHttp3Util.doGet("https://www.zhaoapi.cn/product/deleteCart?uid=2845&pid=" + cartBean.getData().get(i).getList().get(j).getPid(), new Callback() {
@Override
public void onFailure(Call call, IOException e) {

}

@Override
public void onResponse(Call call, Response response) throws IOException {

if (response.isSuccessful()) {
String string = response.body().string();
Log.d("cccc", string);
CommonUtils.runOnUIThread(new Runnable() {
@Override
public void run() {

Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
cartPresenter.getCartData(ApiUtil.cartUrl);


}
});
}
}
});
}
}
}
}

break;
}
}

/**
* 销毁 解决内存泄漏
*/
@Override
protected void onDestroy() {
super.onDestroy();
//解除绑定
if (cartPresenter != null){
cartPresenter.destroy();
}
}
//activity的布局示例

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="wuweixiong.bwie.com.gouwucheexam2.MainActivity">

    <ScrollView
        android:layout_above="@+id/linear_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <!--购物车的二级列表-->
            <wuweixiong.bwie.com.gouwucheexam2.custom.CartExpanableListview
                android:id="@+id/expanable_listview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

            </wuweixiong.bwie.com.gouwucheexam2.custom.CartExpanableListview>

            <!--为你推荐-->
            <LinearLayout
                android:layout_marginTop="20dp"
                android:orientation="vertical"
                android:background="#00ff00"
                android:layout_width="match_parent"
                android:layout_height="500dp">

            </LinearLayout>



        </LinearLayout>


    </ScrollView>

    <RelativeLayout
        android:visibility="gone"
        android:id="@+id/relative_progress"
        android:layout_above="@+id/linear_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </RelativeLayout>

    <LinearLayout
        android:id="@+id/linear_layout"
        android:layout_alignParentBottom="true"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="50dp">
        <CheckBox
            android:layout_marginLeft="10dp"
            android:button="@null"
            android:background="@drawable/check_box_selector"
            android:id="@+id/check_all"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/text_total"
            android:text="合计:¥0.00"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />

        <TextView
            android:text="去结算(0)"
            android:background="#ff0000"
            android:textColor="#ffffff"
            android:gravity="center"
            android:id="@+id/text_buy"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent" />

    </LinearLayout>

</RelativeLayout>

//自定义布局

public class CartExpanableListview extends ExpandableListView {
public CartExpanableListview(Context context) {
super(context);
}

public CartExpanableListview(Context context, AttributeSet attrs) {
super(context, attrs);
}

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

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2,MeasureSpec.AT_MOST);

super.onMeasure(widthMeasureSpec, height);
}
}

public CartExpanableListview(Context context) {
super(context);
}

public CartExpanableListview(Context context, AttributeSet attrs) {
super(context, attrs);
}

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

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2,MeasureSpec.AT_MOST);

super.onMeasure(widthMeasureSpec, height);
}
}

//可能用到的drawable下的xml

//边框

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#fff"/>
    <stroke
        android:width="0.1dp"
        android:color="#000"/>

</shape>
//选项框的xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/shopping_cart_checked"/>
    <item android:state_checked="false" android:drawable="@drawable/shopping_cart_none_check"/>
    <item android:drawable="@drawable/shopping_cart_none_check"/>
</selector>



//适配器:

import android.content.Context;

import android.os.Handler;

import android.os.Message;

import android.view.View;

import android.view.ViewGroup;import android.widget.BaseExpandableListAdapter;import android.widget.CheckBox;import android.widget.ImageView;import android.widget.RelativeLayout;import android.widget.TextView;import com.bumptech.glide.Glide;import java.io.IOException;import java.text.DecimalFormat;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import okhttp3.Call;import okhttp3.Callback;import okhttp3.Response;

/** *  * -------------------注意 价格计算的是打折价格 bargin price----------- * */public class MyAdapter extends BaseExpandableListAdapter{ private RelativeLayout relative_progress; private CartPresenter cartPresenter; private Handler handler; private CartBean cartBean; private Context context; private int size; private int childI; private int allSize; private int index; public MyAdapter(Context context, CartBean cartBean, Handler handler, CartPresenter cartPresenter, RelativeLayout relative_progress) { this.context = context; this.cartBean = cartBean; this.handler = handler; this.cartPresenter = cartPresenter; this.relative_progress = relative_progress; } @Override public int getGroupCount() { return cartBean.getData().size(); } @Override public int getChildrenCount(int groupPosition) { return cartBean.getData().get(groupPosition).getList().size(); } @Override public Object getGroup(int groupPosition) { return cartBean.getData().get(groupPosition); } @Override public Object getChild(int groupPosition, int childPosition) { return cartBean.getData().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 true; } @Override public View getGroupView(int groupPosition, boolean b, View view, ViewGroup viewGroup) { final GroupHolder holder; if (view == null){ view = View.inflate(context, R.layout.group_item_layout,null); holder = new GroupHolder(); holder.check_group = view.findViewById(R.id.check_group); holder.text_group = view.findViewById(R.id.text_group); view.setTag(holder); }else { holder = (GroupHolder) view.getTag(); } final CartBean.DataBean dataBean = cartBean.getData().get(groupPosition); //赋值 holder.check_group.setChecked(dataBean.isGroupChecked()); holder.text_group.setText(dataBean.getSellerName()); //组的点击事件...也要去请求更新的接口 holder.check_group.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { relative_progress.setVisibility(View.VISIBLE);//显示 size = dataBean.getList().size(); childI = 0; updateAllInGroup(holder.check_group.isChecked(),dataBean); } }); return view; }

/** * 更新一组的状态 * @param checked * @param dataBean */ private void updateAllInGroup(final boolean checked, final CartBean.DataBean dataBean) { CartBean.DataBean.ListBean listBean = dataBean.getList().get(childI);//0 //?uid=71&sellerid=1&pid=1&selected=0&num=10 Map<String, String> params = new HashMap<>(); params.put("uid","2845"); params.put("sellerid", String.valueOf(listBean.getSellerid())); params.put("pid", String.valueOf(listBean.getPid())); params.put("selected", String.valueOf(checked ? 1:0)); params.put("num", String.valueOf(listBean.getNum())); OkHttp3Util.doPost(ApiUtil.updateCartUrl, params, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()){ childI = childI+1;//0,1,2...3 if (childI <size){ updateAllInGroup(checked,dataBean); }else { //所有的条目已经更新完成....再次请求查询购物车的数据 cartPresenter.getCartData(ApiUtil.cartUrl); } } } }); } @Override public View getChildView(int groupPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) { ChildHolder holder; if (view == null){ view = View.inflate(context, R.layout.child_item_layout,null); holder = new ChildHolder(); holder.text_add = view.findViewById(R.id.text_add); holder.text_num = view.findViewById(R.id.text_num); holder.text_jian = view.findViewById(R.id.text_jian); holder.text_title = view.findViewById(R.id.text_title); holder.text_price = view.findViewById(R.id.text_price); holder.image_good = view.findViewById(R.id.image_good); holder.check_child = view.findViewById(R.id.check_child); holder.text_delete = view.findViewById(R.id.text_delete); view.setTag(holder); }else { holder = (ChildHolder) view.getTag(); } //赋值 final CartBean.DataBean.ListBean listBean = cartBean.getData().get(groupPosition).getList().get(childPosition); holder.text_num.setText(listBean.getNum()+"");//......注意 holder.text_price.setText("¥"+listBean.getBargainPrice()); holder.text_title.setText(listBean.getTitle()); //listBean.getSelected().....0false,,,1true //设置checkBox选中状态 holder.check_child.setChecked(listBean.getSelected()==0? false:true); /*implementation 'com.github.bumptech.glide:glide:4.4.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.4.0'*/ Glide.with(context).load(listBean.getImages().split("\\|")[0]).into(holder.image_good); //点击事件 holder.check_child.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //点击的时候 更新当前条目选中的状态,,,更新完之后,请求查询购物车,重新展示数据 updateChildChecked(listBean); } }); //加号 holder.text_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //请求更新的接口 updateChildNum(listBean,true); } }); //减号 holder.text_jian.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (listBean.getNum() == 1){ return; } //更新数量,,,减 updateChildNum(listBean,false); } }); return view; } /** * 更新数量 * @param listBean * @param */ private void updateChildNum(CartBean.DataBean.ListBean listBean, boolean isAdded) { //一旦执行更新的操作,,,progressBar显示 relative_progress.setVisibility(View.VISIBLE); //?uid=71&sellerid=1&pid=1&selected=0&num=10 Map<String, String> params = new HashMap<>(); params.put("uid","2845"); params.put("sellerid", String.valueOf(listBean.getSellerid())); params.put("pid", String.valueOf(listBean.getPid())); params.put("selected", String.valueOf(listBean.getSelected())); if (isAdded){ params.put("num", String.valueOf(listBean.getNum() + 1)); }else { params.put("num", String.valueOf(listBean.getNum() - 1)); } OkHttp3Util.doPost(ApiUtil.updateCartUrl, params, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { //更新成功之后...网络上的数据发生了改变...再次请求购物车的接口进行数据的展示 if (response.isSuccessful()){ cartPresenter.getCartData(ApiUtil.cartUrl); } } }); } /** * 更新子条目 网络上的状态 * @param listBean */ private void updateChildChecked(CartBean.DataBean.ListBean listBean) { //一旦执行更新的操作,,,progressBar显示 relative_progress.setVisibility(View.VISIBLE); //?uid=71&sellerid=1&pid=1&selected=0&num=10 Map<String, String> params = new HashMap<>(); params.put("uid","2845"); params.put("sellerid", String.valueOf(listBean.getSellerid())); params.put("pid", String.valueOf(listBean.getPid())); params.put("selected", String.valueOf(listBean.getSelected() == 0? 1:0)); params.put("num", String.valueOf(listBean.getNum())); OkHttp3Util.doPost(ApiUtil.updateCartUrl, params, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { //更新成功之后...网络上的数据发生了改变...再次请求购物车的接口进行数据的展示 if (response.isSuccessful()){ cartPresenter.getCartData(ApiUtil.cartUrl); } } }); } @Override public boolean isChildSelectable(int i, int i1) { return true; } /** * 计算价格和数量 并发送显示 */ public void sendPriceAndCount() { double price = 0; int count = 0; //通过判断二级列表是否勾选,,,,计算价格数量 for (int i=0;i<cartBean.getData().size();i++){ for (int j = 0;j<cartBean.getData().get(i).getList().size();j++){ if (cartBean.getData().get(i).getList().get(j).getSelected() == 1){ //价格是打折的价格........... price += cartBean.getData().get(i).getList().get(j).getNum() * cartBean.getData().get(i).getList().get(j).getBargainPrice(); count += cartBean.getData().get(i).getList().get(j).getNum(); } } } //精准的保留double的两位小数 DecimalFormat decimalFormat = new DecimalFormat("#.00"); String priceString = decimalFormat.format(price); CountPriceBean countPriceBean = new CountPriceBean(priceString, count); //发送...显示 Message msg = Message.obtain(); msg.what = 0; msg.obj = countPriceBean; handler.sendMessage(msg); } /** * 根据全选的状态,,,,跟新每一个子条目的状态,,,全部更新完成后,查询购物车的数据进行展示 * @param checked */ public void setAllChildState(boolean checked) { //创建一个集合 装所有的子条目 List<CartBean.DataBean.ListBean> allList = new ArrayList<>(); for (int i=0;i<cartBean.getData().size();i++){ for (int j=0;j<cartBean.getData().get(i).getList().size();j++){ allList.add(cartBean.getData().get(i).getList().get(j)); } } relative_progress.setVisibility(View.VISIBLE); allSize = allList.size(); index = 0; //通过 递归 更新所有子条目的选中 updateAllChild(allList,checked); } /** * 根据全选 跟新所有的子条目 * @param allList * @param checked */ private void updateAllChild(final List<CartBean.DataBean.ListBean> allList, final boolean checked) { CartBean.DataBean.ListBean listBean = allList.get(index);//0 //跟新的操作 //?uid=71&sellerid=1&pid=1&selected=0&num=10 Map<String, String> params = new HashMap<>(); params.put("uid","2845"); params.put("sellerid", String.valueOf(listBean.getSellerid())); params.put("pid", String.valueOf(listBean.getPid())); params.put("selected", String.valueOf(checked ? 1:0)); params.put("num", String.valueOf(listBean.getNum())); OkHttp3Util.doPost(ApiUtil.updateCartUrl, params, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()){ index = index +1;//0,1,2......3 if (index < allSize){ updateAllChild(allList,checked); }else { //查询购物车 cartPresenter.getCartData(ApiUtil.cartUrl); } } } }); } private class GroupHolder{ CheckBox check_group; TextView text_group; } private class ChildHolder{ CheckBox check_child; ImageView image_good; TextView text_title; TextView text_price; TextView text_jian; TextView text_num; TextView text_add; TextView text_delete; }

}

//一级列表:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:padding="10dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

    <TextView
        android:layout_marginLeft="10dp"
        android:text="京东自营"
        android:id="@+id/text_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>
//二级列表:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/rel"
        android:layout_toLeftOf="@+id/text_delete"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <CheckBox
            android:layout_centerVertical="true"
            android:id="@+id/check_child"
            android:button="@null"
            android:background="@drawable/check_box_selector"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <ImageView
            android:id="@+id/image_good"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/check_child"
            android:layout_marginLeft="10dp"
            android:layout_width="80dp"
            android:layout_height="80dp" />

        <TextView
            android:id="@+id/text_title"
            android:layout_toRightOf="@+id/image_good"
            android:layout_marginLeft="10dp"
            android:layout_alignTop="@+id/image_good"
            android:maxLines="2"
            android:minLines="2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/text_price"
            android:layout_toRightOf="@+id/image_good"
            android:layout_marginLeft="10dp"
            android:layout_alignBottom="@+id/image_good"
            android:text="¥99.99"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <LinearLayout
            android:layout_alignParentRight="true"
            android:layout_alignBottom="@+id/image_good"
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/text_jian"
                android:text=""
                android:padding="5dp"
                android:background="@drawable/bian_kuang_line"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <TextView
                android:gravity="center"
                android:id="@+id/text_num"
                android:paddingLeft="10dp"
                android:paddingRight="10dp"
                android:background="@drawable/bian_kuang_line"
                android:layout_width="wrap_content"
                android:layout_height="match_parent" />

            <TextView
                android:id="@+id/text_add"
                android:text=""
                android:padding="5dp"
                android:background="@drawable/bian_kuang_line"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>

    </RelativeLayout>

    <TextView
        android:layout_marginLeft="3dp"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/rel"
        android:layout_alignBottom="@+id/rel"
        android:id="@+id/text_delete"
        android:text="删除"
        android:gravity="center"
        android:layout_width="50dp"
        android:background="#793"
        android:layout_height="wrap_content" />


</RelativeLayout>

//计算价格时用到的bean包

public class CountPriceBean {
private String priceString;
private int count;

public CountPriceBean(String priceString, int count) {
this.priceString = priceString;
this.count = count;
}

public String getPriceString() {
return priceString;
}

public void setPriceString(String priceString) {
this.priceString = priceString;
}

public int getCount() {
return count;
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值