仿京東Cart

Model 請求數據

import android.util.Log;

import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
/**
* 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;
/**
* 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);
}
}
}

接口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.csdn.net/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;
}
}

//CartBean
//在DataBean裏面調價了4行代碼,用於點擊
// private boolean isGroupChecked;//一級列表是否選中
// public boolean isGroupChecked() {
// return isGroupChecked;
// }

// public void setGroupChecked(boolean groupChecked) {
// isGroupChecked = groupChecked;
// }

public class CartBean {

    /**
     * msg : 請求成功
     * code : 0
     * data : [{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":22,"price":799,"pscid":1,"selected":0,"sellerid":15,"subhead":"每個中秋都不能簡單,無論身在何處,你總需要一塊餅讓生活更圓滿,京東月餅讓愛更圓滿京東自營,閃電配送,更多驚喜,快用手指戳一下","title":"北京稻香村 稻香村中秋節月餅 老北京月餅禮盒655g"}],"sellerName":"商家15","sellerid":"15"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":1,"price":118,"pscid":1,"selected":0,"sellerid":17,"subhead":"每個中秋都不能簡單,無論身在何處,你總需要一塊餅讓生活更圓滿,京東月餅讓愛更圓滿京東自營,閃電配送,更多驚喜,快用手指戳一下","title":"北京稻香村 稻香村中秋節月餅 老北京月餅禮盒655g"}],"sellerName":"商家17","sellerid":"17"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":2,"price":299,"pscid":1,"selected":0,"sellerid":18,"subhead":"每個中秋都不能簡單,無論身在何處,你總需要一塊餅讓生活更圓滿,京東月餅讓愛更圓滿京東自營,閃電配送,更多驚喜,快用手指戳一下","title":"北京稻香村 稻香村中秋節月餅 老北京月餅禮盒655g"}],"sellerName":"商家18","sellerid":"18"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":4,"price":999,"pscid":1,"selected":0,"sellerid":20,"subhead":"每個中秋都不能簡單,無論身在何處,你總需要一塊餅讓生活更圓滿,京東月餅讓愛更圓滿京東自營,閃電配送,更多驚喜,快用手指戳一下","title":"北京稻香村 稻香村中秋節月餅 老北京月餅禮盒655g"}],"sellerName":"商家20","sellerid":"20"}]
     */

    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 {
        public boolean isGroupChecked() {
            return isGroupChecked;
        }

        public void setGroupChecked(boolean groupChecked) {
            isGroupChecked = groupChecked;
        }

        /**
         * list : [{"bargainPrice":111.99,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":22,"price":799,"pscid":1,"selected":0,"sellerid":15,"subhead":"每個中秋都不能簡單,無論身在何處,你總需要一塊餅讓生活更圓滿,京東月餅讓愛更圓滿京東自營,閃電配送,更多驚喜,快用手指戳一下","title":"北京稻香村 稻香村中秋節月餅 老北京月餅禮盒655g"}]
         * sellerName : 商家15
         * sellerid : 15
         */


        private boolean isGroupChecked;//一級列表是否選中



        private String sellerName;
        private String sellerid;
        private List<ListBean> list;

        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 {
            /**
             * bargainPrice : 111.99
             * createtime : 2017-10-14T21:48:08
             * detailUrl : https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends
             * images : https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg
             * num : 1
             * pid : 22
             * price : 799.0
             * pscid : 1
             * selected : 0
             * sellerid : 15
             * subhead : 每個中秋都不能簡單,無論身在何處,你總需要一塊餅讓生活更圓滿,京東月餅讓愛更圓滿京東自營,閃電配送,更多驚喜,快用手指戳一下
             * title : 北京稻香村 稻香村中秋節月餅 老北京月餅禮盒655g
             */

            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;//判斷二級是否選中,,,1選中,0未選中


            private int sellerid;
            private String subhead;
            private String title;

            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;
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章