点击图片放大跳转页面

activity_auto

<?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="com.bwie.test.autodemo.AutoActivity">
    <TextView
        android:id="@+id/gou"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="10dp"
        android:text="购物车"
        android:textSize="16dp" />

    <View
        android:id="@+id/vx"
        android:layout_width="match_parent"
        android:layout_height="0.1dp"
        android:layout_below="@id/gou"
        android:background="#000" />

    <RelativeLayout
        android:id="@+id/relative_progress"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:visibility="invisible">

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

    <com.bwie.test.util.MyExpanableListView
        android:id="@+id/myrecycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/vx">
    </com.bwie.test.util.MyExpanableListView>

    <LinearLayout
        android:id="@+id/xxx"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:background="#fff"
        android:orientation="horizontal">
        <CheckBox
            android:id="@+id/check_all"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp" />

        <TextView
            android:id="@+id/text_total"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="10dp"
            android:layout_weight="1"
            android:text="合计:¥0.00" />

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

    </LinearLayout>
</RelativeLayout>

activity_new_map

<?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="com.bwie.test.autodemo.NewMapActivity">
    <com.bwie.test.util.LargeImageView
        android:id="@+id/id_largetImageview"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </com.bwie.test.util.LargeImageView>

</RelativeLayout>

cart_childitem

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

    <CheckBox
        android:id="@+id/child_check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true" />

    <ImageView
        android:id="@+id/child_image"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@+id/child_check" />

    <TextView
        android:id="@+id/child_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@+id/child_image"
        android:maxLines="2"
        android:minLines="2" />

    <TextView
        android:id="@+id/child_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/child_image"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@+id/child_image"
        android:text="¥0.00"
        android:textColor="#ff0000" />

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

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

        <TextView
            android:id="@+id/text_num"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="5dp"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:paddingTop="5dp"
            android:text="1" />

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

    </LinearLayout>
</RelativeLayout>

cart_groupitem

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

    <CheckBox
        android:id="@+id/group_check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" />

    <TextView
        android:id="@+id/group_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp" />

</LinearLayout>

dialog

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="修改购买数量"
        android:textSize="20sp"
        android:gravity="center"
        android:layout_marginTop="10dp"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="10dp">
        <TextView
            android:id="@+id/dialog_jian"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@drawable/bian_kuang_line"
            android:padding="5dp"
            android:text="-"
            android:textSize="20sp"
            android:gravity="center"/>

        <TextView
            android:id="@+id/dialog_num"
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:background="@drawable/bian_kuang_line"
            android:paddingBottom="5dp"
            android:paddingLeft="8dp"
            android:paddingRight="8dp"
            android:paddingTop="5dp"
            android:textSize="20sp"
            android:gravity="center"/>

        <TextView
            android:id="@+id/dialog_add"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@drawable/bian_kuang_line"
            android:padding="5dp"
            android:text="+"
            android:textSize="20sp"
            android:gravity="center"/>
    </LinearLayout>
</LinearLayout>

drawable文件夹下bian_kuang_line

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

main创建assets文件夹放置图片world

AutoActivity

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bwie.test.adapter.CartAdapter;
import com.bwie.test.bean.CountPriceBean;
import com.bwie.test.bean.Select_Cart_Bean;
import com.bwie.test.presenter.MainPresenter;
import com.bwie.test.util.Constant;
import com.bwie.test.util.MyExpanableListView;
import com.bwie.test.view.MainInter;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;

public class AutoActivity extends AppCompatActivity implements MainInter{
    @BindView(R.id.myrecycler)
    RecyclerView mMyrecycler;
    @BindView(R.id.check_all)
    CheckBox mCheckAll;
    @BindView(R.id.text_total)
    TextView mTextTotal;
    @BindView(R.id.text_buy)
    TextView mTextBuy;
    private MainPresenter presenter;
    private RelativeLayout relative_progress;
    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() + ")");
            }
        }
    };
    private MyExpanableListView myExpanableListVIew;
    private CheckBox check_all;
    private TextView text_total;
    private TextView text_buy;
    private CartAdapter adapter;
    Select_Cart_Bean bean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auto);
        //隐藏原有标题
        getSupportActionBar().hide();

        initView();
        ButterKnife.bind(this);
        presenter = new MainPresenter(this);
        presenter.attachView(this);
        getData();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("uid", "11439");
        //获取数据
        presenter.getDataFromNet(Constant.SELECT_CART_URL, map);
    }

    @OnClick({R.id.check_all, R.id.text_buy})
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.check_all:
                check_all.setChecked(isAllGroupChecked(bean));
                check_all.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (adapter != null) {
                            adapter.setAllChildChecked(check_all.isChecked());
                        }
                    }
                });
                //展开所有的组...expanableListView.expandGroup()
                for (int y = 0; y < bean.getData().size(); y++) {
                    myExpanableListVIew.expandGroup(y);
                }
                break;
            case R.id.text_buy:
                Intent intent = new Intent(AutoActivity.this, NewMapActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onSuccess(ResponseBody responseBody) {
        Log.d("------TAG", "onSuccess: " + responseBody.toString());
        try {
            String json = responseBody.string();
            Select_Cart_Bean bean = new Gson().fromJson(json, Select_Cart_Bean.class);
            Log.d("------TAG", "onSuccess: " + bean.getMsg());
            Toast.makeText(AutoActivity.this, bean.getMsg(), Toast.LENGTH_SHORT).show();

            //获取数据成功...隐藏
            relative_progress.setVisibility(View.GONE);
            //1.根据某一个组中的二级所有的子条目是否选中,确定当前一级列表是否选中
            for (int j = 0; j < bean.getData().size(); j++) {
                if (isChildInGroupChecked(j, bean)) {
                    bean.getData().get(j).setGroupChecked(true);
                }
            }
            myExpanableListVIew.setGroupIndicator(null);
            adapter = new CartAdapter(AutoActivity.this, bean, presenter, handler, relative_progress);
            myExpanableListVIew.setAdapter(adapter);
            check_all.setChecked(isAllGroupChecked(bean));
            check_all.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (adapter != null) {
                        adapter.setAllChildChecked(check_all.isChecked());
                    }
                }
            });
            //展开所有的组...expanableListView.expandGroup()
            for (int y = 0; y < bean.getData().size(); y++) {
                myExpanableListVIew.expandGroup(y);
            }
            //3.计算总价和商品的数量
            adapter.sendPriceAndCount();

            text_buy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(AutoActivity.this, NewMapActivity.class);
                    startActivity(intent);
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onError(Throwable throwable) {
        Log.e("----", throwable.getMessage());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.unsubcribe();//解除订阅
        if (presenter.isViewAttached()) {//如果产生关联
            //解除关联
            presenter.detachView();
        }
    }

    private void initView() {
        myExpanableListVIew = (MyExpanableListView) findViewById(R.id.myrecycler);
        check_all = (CheckBox) findViewById(R.id.check_all);
        text_total = (TextView) findViewById(R.id.text_total);
        text_buy = (TextView) findViewById(R.id.text_buy);
        relative_progress = (RelativeLayout) findViewById(R.id.relative_progress);
    }

    /**
     * 所有的组是否选中
     */
    private boolean isAllGroupChecked(Select_Cart_Bean bean) {
        for (int i = 0; i < bean.getData().size(); i++) {
            if (!bean.getData().get(i).isGroupChecked()) {//表示有没选中的组
                return false;
            }
        }
        return true;
    }

    /**
     * 当前组中所有的子条目是否全部选中
     */
    private boolean isChildInGroupChecked(int i, Select_Cart_Bean bean) {
        //当前组中所有子条目的数据
        List<Select_Cart_Bean.DataBean.ListBean> listBeans = bean.getData().get(i).getList();
        for (int j = 0; j < listBeans.size(); j++) {
            if (listBeans.get(j).getSelected() == 0) {//有未选中的条目
                return false;
            }
        }
        return true;
    }
}

NewMapActivity

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.bwie.test.util.LargeImageView;

import java.io.IOException;
import java.io.InputStream;

public class NewMapActivity extends AppCompatActivity {
    private LargeImageView mLargeImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_map);
        //查找控件
        mLargeImageView = (LargeImageView) findViewById(R.id.id_largetImageview);
        try {
            InputStream inputStream = getAssets().open("world.jpg");
            mLargeImageView.setInputStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

adapter文件夹下CartAdapter

import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
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 com.bwie.test.bean.CountPriceBean;
import com.bwie.test.bean.Select_Cart_Bean;
import com.bwie.test.presenter.MainPresenter;

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;

import com.bwie.test.autodemo.R;
import com.bwie.test.util.ApiUrils;
import com.bwie.test.util.Constant;
import com.bwie.test.util.OkHttp3Util;

public class CartAdapter extends BaseExpandableListAdapter {
    private RelativeLayout relative_progress;
    private Context context;
    private Select_Cart_Bean bean;
    private MainPresenter presenter;
    private Handler handler;
    private int childIndex;
    private int allIndex;

    public CartAdapter(Context context, Select_Cart_Bean bean, MainPresenter presenter, Handler handler, 
                               RelativeLayout relative_progress) {
        this.context = context;
        this.bean = bean;
        this.relative_progress = relative_progress;
        this.presenter = presenter;
        this.handler = handler;
    }

    @Override
    public int getGroupCount() {
        return bean.getData().size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return bean.getData().get(groupPosition).getList().size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return bean.getData().get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return bean.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 i, boolean b, View view, ViewGroup viewGroup) {
        final GroupHolder holder;
        if (view == null) {
            view = View.inflate(context, R.layout.cart_groupitem, null);
            holder = new GroupHolder();
            holder.checkBox = view.findViewById(R.id.group_check);
            holder.textView = view.findViewById(R.id.group_text);
            view.setTag(holder);
        } else {
            holder = (GroupHolder) view.getTag();
        }
        final Select_Cart_Bean.DataBean dataBean = bean.getData().get(i);
        holder.textView.setText(dataBean.getSellerName());
        holder.checkBox.setChecked(dataBean.isGroupChecked());
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                relative_progress.setVisibility(View.VISIBLE);
                //点击一级列表的时候,子条目需要一个个的去执行更新
                //使用递归的形式...例如组里面3个孩子一,,,0,1,2
                childIndex = 0;
                //更新
                updateChildCheckedInGroup(holder.checkBox.isChecked(), dataBean);
            }
        });
        return view;
    }

    private void updateChildCheckedInGroup(final boolean checked, final Select_Cart_Bean.DataBean 
                                          dataBean) {
        final Select_Cart_Bean.DataBean.ListBean listBean = dataBean.getList().get(childIndex);
        //请求更新购物车的接口...更新成功之后,再次请求查询购物车的接口,进行数据的展示
        //          ?uid=11439&sellerid=1&pid=1&selected=0&num=10
        Map<String, String> params = new HashMap<>();
        params.put("uid", String.valueOf(11439));
        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(ApiUrils.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()) {
                    childIndex++;//0,1,2....size()
                    if (childIndex < dataBean.getList().size()) {
                        //继续更新
                        updateChildCheckedInGroup(checked, dataBean);
                    } else {
                        //请求查询购物车的操作...重新展示数据
                        Map<String, String> map = new HashMap<>();
                        map.put("uid", String.valueOf(11439));
                        presenter.getDataFromNet(Constant.SELECT_CART_URL, map);
                    }
                }
            }
        });
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean b, View view, 
                       ViewGroup viewGroup) {
        final ChildHolder holder;
        if (view == null) {
            view = View.inflate(context, R.layout.cart_childitem, null);
            holder = new ChildHolder();

            holder.checkBox = view.findViewById(R.id.child_check);
            holder.text_title = view.findViewById(R.id.child_title);
            holder.text_price = view.findViewById(R.id.child_price);
            holder.imageView = view.findViewById(R.id.child_image);
            holder.text_num = view.findViewById(R.id.text_num);
            holder.text_jian = view.findViewById(R.id.text_jian);
            holder.text_add = view.findViewById(R.id.text_add);
            view.setTag(holder);
        } else {
            holder = (ChildHolder) view.getTag();
        }
        final Select_Cart_Bean.DataBean.ListBean listBean = bean.getData().get(groupPosition)
                        .getList().get(childPosition);
        //赋值
        holder.text_title.setText(listBean.getTitle());
        holder.text_price.setText("¥" + listBean.getBargainPrice());
        String[] strings = listBean.getImages().split("\\|");
//        Uri uri = Uri.parse(strings[0]);
//        holder.imageView.setImageURI(uri);
        Glide.with(context).load(strings[0]).into(holder.imageView);
        holder.checkBox.setChecked(listBean.getSelected() == 0 ? false : true);//根据0,1进行设置是否选中
        holder.text_num.setText(listBean.getNum() + "");
        holder.text_num.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(context);
                View inflate = View.inflate(context, R.layout.dialog, null);
                builder.setView(inflate);
                TextView dialog_add = inflate.findViewById(R.id.dialog_add);
                final TextView dialog_jian = inflate.findViewById(R.id.dialog_jian);
                final TextView dialog_num = inflate.findViewById(R.id.dialog_num);
                dialog_num.setText(listBean.getNum() + "");
                dialog_add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String number = dialog_num.getText().toString();
                        int num = Integer.parseInt(number);
                        num++;
                        dialog_num.setText(num + "");
                        notifyDataSetChanged();
                    }
                });

                dialog_jian.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String number = dialog_num.getText().toString();
                        int i = Integer.parseInt(number);
                        if (i > 1) {
                            i--;
                            dialog_num.setText(i + "");
                            return;
                        }
                        notifyDataSetChanged();
                    }
                });

                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String s = dialog_num.getText().toString();
                        holder.text_num.setText(s);
                        listBean.setNum(Integer.parseInt(s));
                        relative_progress.setVisibility(View.VISIBLE);
                        Map<String, String> params = new HashMap<>();
                        //?uid=71&sellerid=1&pid=1&selected=0&num=10
                        params.put("uid", "11439");
                        params.put("sellerid", String.valueOf(listBean.getSellerid()));
                        params.put("pid", String.valueOf(listBean.getPid()));
                        params.put("selected", String.valueOf(listBean.getSelected()));
                        params.put("num", String.valueOf(s));

                        OkHttp3Util.doPost(ApiUrils.UPDATE_CART_URL, params, new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {

                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                if (response.isSuccessful()) {
                                    //请求查询购物车的操作...重新展示数据
                                    Map<String, String> map = new HashMap<>();
                                    map.put("uid", "11439");
                                    presenter.getDataFromNet(Constant.SELECT_CART_URL, map);
                                }
                            }
                        });
                    }
                });

                builder.setNegativeButton("取消", null);
                builder.show();
            }
        });

        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //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", String.valueOf(11439));
                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(ApiUrils.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()) {
                            Map<String, String> map = new HashMap<>();
                            map.put("uid", "11439");
                            presenter.getDataFromNet(Constant.SELECT_CART_URL, map);
                        }
                    }
                });
            }
        });

        //加
        holder.text_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //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", String.valueOf(11439));
                params.put("sellerid", String.valueOf(listBean.getSellerid()));
                params.put("pid", String.valueOf(listBean.getPid()));
                params.put("selected", String.valueOf(listBean.getSelected()));
                params.put("num", String.valueOf(listBean.getNum() + 1));

                OkHttp3Util.doPost(ApiUrils.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()) {
                            Map<String, String> map = new HashMap<>();
                            map.put("uid", "11439");
                            presenter.getDataFromNet(Constant.SELECT_CART_URL, map);
                        }
                    }
                });
            }
        });

        //减
        holder.text_jian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int num = listBean.getNum();
                if (num == 1) {
                    return;
                }
                //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", String.valueOf(11439));
                params.put("sellerid", String.valueOf(listBean.getSellerid()));
                params.put("pid", String.valueOf(listBean.getPid()));
                params.put("selected", String.valueOf(listBean.getSelected()));
                params.put("num", String.valueOf(num - 1));

                OkHttp3Util.doPost(ApiUrils.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()) {
                            Map<String, String> map = new HashMap<>();
                            map.put("uid", "11439");
                            presenter.getDataFromNet(Constant.SELECT_CART_URL, map);
                        }
                    }
                });
            }
        });
        return view;
    }

    /**
     * 计算数量和价格,,,并发送到activity显示
     */
    public void sendPriceAndCount() {
        double price = 0;
        int count = 0;

        for (int i = 0; i < bean.getData().size(); i++) {
            List<Select_Cart_Bean.DataBean.ListBean> listBeans = bean.getData().get(i).getList();
            for (int j = 0; j < listBeans.size(); j++) {
                Select_Cart_Bean.DataBean.ListBean listBean = listBeans.get(j);
                //选中的时候计算价格和数量
                if (listBean.getSelected() == 1) {
                    price += listBean.getBargainPrice() * listBean.getNum();
                    count += listBean.getNum();
                }
            }
        }
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        String priceString = decimalFormat.format(price);
        //封装一下
        CountPriceBean countPriceBean = new CountPriceBean(priceString, count);
        //发送给activity/fragment进行显示
        Message msg = Message.obtain();
        msg.what = 0;
        msg.obj = countPriceBean;
        handler.sendMessage(msg);
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    /**
     * 更新所有的子孩子的状态...跟随全选状态改变
     * @param checked
     */
    public void setAllChildChecked(boolean checked) {
        //显示进度条
        relative_progress.setVisibility(View.VISIBLE);
        //通过遍历,把所有的孩子装到一个大的集合中
        List<Select_Cart_Bean.DataBean.ListBean> allList = new ArrayList<>();
        for (int i = 0; i < bean.getData().size(); i++) {
            for (int j = 0; j < bean.getData().get(i).getList().size(); j++) {
                allList.add(bean.getData().get(i).getList().get(j));
            }
        }
        //更新每一个子孩子的状态...递归
        allIndex = 0;
        updateAllChild(checked, allList);
    }

    /**
     * 更新所有的孩子
     * @param checked
     * @param allList
     */
    private void updateAllChild(final boolean checked, final List<Select_Cart_Bean.DataBean.ListBean> 
                                            allList) {
        Select_Cart_Bean.DataBean.ListBean listBean = allList.get(allIndex);
        //请求更新购物车的接口...更新成功之后,再次请求查询购物车的接口,进行数据的展示
        //?uid=71&sellerid=1&pid=1&selected=0&num=10
        Map<String, String> params = new HashMap<>();
        params.put("uid", String.valueOf(11439));
        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(ApiUrils.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()) {
                    allIndex++;
                    //判断
                    if (allIndex < allList.size()) {
                        //继续更新
                        updateAllChild(checked, allList);
                    } else {
                        Map<String, String> map = new HashMap<>();
                        map.put("uid", "11439");
                        presenter.getDataFromNet(Constant.SELECT_CART_URL, map);
                    }
                }
            }
        });
    }

    private class GroupHolder {
        CheckBox checkBox;
        TextView textView;
    }

    private class ChildHolder {
        CheckBox checkBox;
        ImageView imageView;
        TextView text_title;
        TextView text_price;
        TextView text_num;
        TextView text_jian;
        TextView text_add;
    }
}

model文件夹下BaseMain

import java.util.Map;

public interface BaseMain {
    void getDataFromNet(String url, Map<String, String> map);
    void unsubcribe();
}

MainModel

import com.bwie.test.presenter.PersenterInter;
import com.bwie.test.util.RetrofitUtil;
import java.util.Map;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

public class MainModel implements BaseMain{
    public Disposable d;
    private PersenterInter persenterInter;

    public MainModel(PersenterInter persenterInter) {
        this.persenterInter = persenterInter;
    }

    @Override
    public void getDataFromNet(String url, Map<String, String> map) {
        RetrofitUtil.getService()
                .doPost(url, map)
                .subscribeOn(Schedulers.io())//在io线程获取数据
                .observeOn(AndroidSchedulers.mainThread())//在android主线程梳理数据
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        MainModel.this.d = d;
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        persenterInter.onSuccess(responseBody);
                    }

                    @Override
                    public void onError(Throwable e) {
                        persenterInter.onError(e);
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    @Override
    public void unsubcribe() {
        d.dispose();
    }
}

presenter文件夹下BasePresenter

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

public abstract class BasePresenter<T> {
    protected Reference<T> mViewRef;//View接口类型弱引用

    public void attachView(T view) {
        mViewRef = new WeakReference<T>(view); //建立关联
    }

    protected T getView() {
        return mViewRef.get();//获取View
    }

    public boolean isViewAttached() {//判断是否与View建立了关联
        return mViewRef != null && mViewRef.get() != null;
    }

    public void detachView() {//解除关联
        if (mViewRef != null) {
            mViewRef.clear();
            mViewRef = null;
        }
    }
}

MainPresenter

import com.bwie.test.model.MainModel;
import com.bwie.test.view.MainInter;
import java.util.Map;
import okhttp3.ResponseBody;

public class MainPresenter extends BasePresenter implements PersenterInter{
    private final MainModel mainModel;
    private MainInter mainInter;

    public MainPresenter(MainInter mainInter) {
        this.mainInter = mainInter;
        mainModel = new MainModel(this);
    }

    @Override
    public void onSuccess(ResponseBody responseBody) {
        mainInter.onSuccess(responseBody);
    }

    @Override
    public void onError(Throwable e) {
        mainInter.onError(e);
    }

    @Override
    public void getDataFromNet(String url, Map<String, String> map) {
        mainModel.getDataFromNet(url,map);
    }

    @Override
    public void unsubcribe() {
        mainModel.unsubcribe();
    }
}

PersenterInter

import java.util.Map;
import okhttp3.ResponseBody;

public interface PersenterInter {
    void onSuccess(ResponseBody responseBody);
    void onError(Throwable e);

    void getDataFromNet(String url, Map<String, String> map);
    void unsubcribe();
}

view文件夹下MainInter

import okhttp3.ResponseBody;

public interface MainInter {
    void onSuccess(ResponseBody responseBody);
    void onError(Throwable throwable);
}

util文件夹下ApiService

import java.util.Map;
import io.reactivex.Observable;
import okhttp3.ResponseBody;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
import retrofit2.http.Path;

public interface ApiService {
    @FormUrlEncoded
    @POST("{url}")
    Observable<ResponseBody> doPost(@Path(value = "url", encoded = true) String url, @FieldMap Map<String, 
                     String> map);
}

ApiUrils

public class ApiUrils {
    //更新购物车             ?uid=71&sellerid=1&pid=1&selected=0&num=10
    public static String updateCartUrl = "https://www.zhaoapi.cn/product/updateCarts";
    //添加购物车                        ?uid=11439&pid=12&source=android
    public static String addCartUrl = "https://www.zhaoapi.cn/product/addCart";
    //删除购物车                                                                  ?uid=72&pid=1
    public static String deleCartUrl = "https://www.zhaoapi.cn/product/deleteCart";
    //更新购物车 product/updateCarts?uid=71&sellerid=1&pid=1&selected=0&num=10
    public static final String UPDATE_CART_URL = "https://www.zhaoapi.cn/"+"product/updateCarts";
}

BaseGestureDetector

import android.content.Context;
import android.view.MotionEvent;

public abstract class BaseGestureDetector {
    protected boolean mGestureInProgress;
    protected MotionEvent mPreMotionEvent;
    protected MotionEvent mCurrentMotionEvent;
    protected Context mContext;

    public BaseGestureDetector(Context context) {
        mContext = context;
    }

    public boolean onToucEvent(MotionEvent event) {
        if (!mGestureInProgress) {
            handleStartProgressEvent(event);
        } else {
            handleInProgressEvent(event);
        }
        return true;
    }

    protected abstract void handleInProgressEvent(MotionEvent event);

    protected abstract void handleStartProgressEvent(MotionEvent event);

    protected abstract void updateStateByEvent(MotionEvent event);

    protected void resetState() {
        if (mPreMotionEvent != null) {
            mPreMotionEvent.recycle();
            mPreMotionEvent = null;
        }
        if (mCurrentMotionEvent != null) {
            mCurrentMotionEvent.recycle();
            mCurrentMotionEvent = null;
        }
        mGestureInProgress = false;
    }
}

Constant

public class Constant {
    public static final String BASE_URL = "https://www.zhaoapi.cn/";
    public static final String SELECT_CART_URL = "product/getCarts";
}

LargeImageView

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.io.IOException;
import java.io.InputStream;

public class LargeImageView extends View {
    private BitmapRegionDecoder mDecoder;
    /**
     * 图片的宽度和高度
     */
    private int mImageWidth, mImageHeight;
    /**
     * 绘制的区域
     */
    private volatile Rect mRect = new Rect();
    private MoveGestureDetector mDetector;

    private static final BitmapFactory.Options options = new BitmapFactory.Options();

    static {
        options.inPreferredConfig = Bitmap.Config.RGB_565;
    }

    public void setInputStream(InputStream is) {
        try {
            mDecoder = BitmapRegionDecoder.newInstance(is, false);
            BitmapFactory.Options tmpOptions = new BitmapFactory.Options();
            // Grab the bounds for the scene dimensions
            tmpOptions.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(is, null, tmpOptions);
            mImageWidth = tmpOptions.outWidth;
            mImageHeight = tmpOptions.outHeight;
            requestLayout();
            invalidate();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
            } catch (Exception e) {
            }
        }
    }

    public void init() {
        mDetector = new MoveGestureDetector(getContext(), new 
                                    MoveGestureDetector.SimpleMoveGestureDetector() {
            @Override
            public boolean onMove(MoveGestureDetector detector) {
                int moveX = (int) detector.getMoveX();
                int moveY = (int) detector.getMoveY();
                if (mImageWidth > getWidth()) {
                    mRect.offset(-moveX, 0);
                    checkWidth();
                    invalidate();
                }
                if (mImageHeight > getHeight()) {
                    mRect.offset(0, -moveY);
                    checkHeight();
                    invalidate();
                }
                return true;
            }
        });
    }

    private void checkWidth() {
        Rect rect = mRect;
        int imageWidth = mImageWidth;
        int imageHeight = mImageHeight;
        if (rect.right > imageWidth) {
            rect.right = imageWidth;
            rect.left = imageWidth - getWidth();
        }
        if (rect.left < 0) {
            rect.left = 0;
            rect.right = getWidth();
        }
    }

    private void checkHeight() {
        Rect rect = mRect;
        int imageWidth = mImageWidth;
        int imageHeight = mImageHeight;
        if (rect.bottom > imageHeight) {
            rect.bottom = imageHeight;
            rect.top = imageHeight - getHeight();
        }
        if (rect.top < 0) {
            rect.top = 0;
            rect.bottom = getHeight();
        }
    }

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

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mDetector.onToucEvent(event);
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Bitmap bm = mDecoder.decodeRegion(mRect, options);
        canvas.drawBitmap(bm, 0, 0, null);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        int imageWidth = mImageWidth;
        int imageHeight = mImageHeight;

        //默认直接显示图片的中心区域,可以自己去调节
        mRect.left = imageWidth / 2 - width / 2;
        mRect.top = imageHeight / 2 - height / 2;
        mRect.right = mRect.left + width;
        mRect.bottom = mRect.top + height;
    }
}

MoveGestureDetector

import android.content.Context;
import android.graphics.PointF;
import android.view.MotionEvent;

public class MoveGestureDetector extends BaseGestureDetector {
    private PointF mCurrentPointer;
    private PointF mPrePointer;
    //仅仅为了减少创建内存
    private PointF mDeltaPointer = new PointF();
    //用于记录最终结果,并返回
    private PointF mExtenalPointer = new PointF();
    private OnMoveGestureListener mListenter;

    public MoveGestureDetector(Context context, OnMoveGestureListener listener) {
        super(context);
        mListenter = listener;
    }

    @Override
    protected void handleInProgressEvent(MotionEvent event) {
        int actionCode = event.getAction() & MotionEvent.ACTION_MASK;
        switch (actionCode) {
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                mListenter.onMoveEnd(this);
                resetState();
                break;
            case MotionEvent.ACTION_MOVE:
                updateStateByEvent(event);
                boolean update = mListenter.onMove(this);
                if (update) {
                    mPreMotionEvent.recycle();
                    mPreMotionEvent = MotionEvent.obtain(event);
                }
                break;
        }
    }

    @Override
    protected void handleStartProgressEvent(MotionEvent event) {
        int actionCode = event.getAction() & MotionEvent.ACTION_MASK;
        switch (actionCode) {
            case MotionEvent.ACTION_DOWN:
                resetState();//防止没有接收到CANCEL or UP ,保险起见
                mPreMotionEvent = MotionEvent.obtain(event);
                updateStateByEvent(event);
                break;
            case MotionEvent.ACTION_MOVE:
                mGestureInProgress = mListenter.onMoveBegin(this);
                break;
        }
    }

    protected void updateStateByEvent(MotionEvent event) {
        final MotionEvent prev = mPreMotionEvent;

        mPrePointer = caculateFocalPointer(prev);
        mCurrentPointer = caculateFocalPointer(event);
        //Log.e("TAG", mPrePointer.toString() + " ,  " + mCurrentPointer);
        boolean mSkipThisMoveEvent = prev.getPointerCount() != event.getPointerCount();
        //Log.e("TAG", "mSkipThisMoveEvent = " + mSkipThisMoveEvent);
        mExtenalPointer.x = mSkipThisMoveEvent ? 0 : mCurrentPointer.x - mPrePointer.x;
        mExtenalPointer.y = mSkipThisMoveEvent ? 0 : mCurrentPointer.y - mPrePointer.y;
    }

    /**
     * 根据event计算多指中心点
     * @param event
     * @return
     */
    private PointF caculateFocalPointer(MotionEvent event) {
        final int count = event.getPointerCount();
        float x = 0, y = 0;
        for (int i = 0; i < count; i++) {
            x += event.getX(i);
            y += event.getY(i);
        }
        x /= count;
        y /= count;
        return new PointF(x, y);
    }

    public float getMoveX() {
        return mExtenalPointer.x;
    }

    public float getMoveY() {
        return mExtenalPointer.y;
    }

    public interface OnMoveGestureListener {
        public boolean onMoveBegin(MoveGestureDetector detector);
        public boolean onMove(MoveGestureDetector detector);
        public void onMoveEnd(MoveGestureDetector detector);
    }

    public static class SimpleMoveGestureDetector implements OnMoveGestureListener {
        @Override
        public boolean onMoveBegin(MoveGestureDetector detector) {
            return true;
        }

        @Override
        public boolean onMove(MoveGestureDetector detector) {
            return false;
        }

        @Override
        public void onMoveEnd(MoveGestureDetector detector) {
        }
    }
}

MyExpanableListView

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ExpandableListView;

public class MyExpanableListView extends ExpandableListView {

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

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

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

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

OkHttp3Util

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttp3Util {
    private static OkHttpClient okHttpClient = null;

    private OkHttp3Util() {
    }

    public static OkHttpClient getInstance() {
        if (okHttpClient == null) {
            //加同步安全
            synchronized (OkHttp3Util.class) {
                if (okHttpClient == null) {
                    //okhttp可以缓存数据....指定缓存路径
                    File sdcache = new File(Environment.getExternalStorageDirectory(), "cache");
                    //指定缓存大小
                    int cacheSize = 10 * 1024 * 1024;
                    okHttpClient = new OkHttpClient.Builder()//构建器
                            .connectTimeout(15, TimeUnit.SECONDS)//连接超时
                            .writeTimeout(20, TimeUnit.SECONDS)//写入超时
                            .readTimeout(20, TimeUnit.SECONDS)//读取超时
                            .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))
                            .build();
                }
            }
        }
        return okHttpClient;
    }

    /**
     * get请求
     * 参数1 url
     * 参数2 回调Callback
     */
    public static void doGet(String oldUrl, Callback callback) {

        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = getInstance();
        //创建Request
        Request request = new Request.Builder().url(oldUrl).build();
        //得到Call对象
        Call call = okHttpClient.newCall(request);
        //执行异步请求
        call.enqueue(callback);
    }
    /**
     * post请求
     * 参数1 url
     * 参数2 Map<String, String> params post请求的时候给服务器传的数据
     *      add..("","")
     *      add()
     */
    public static void doPost(String url, Map<String, String> params, Callback callback) {
        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = getInstance();
        //3.x版本post请求换成FormBody 封装键值对参数
        FormBody.Builder builder = new FormBody.Builder();
        //遍历集合,,,map集合遍历方式
        for (String key : params.keySet()) {
            builder.add(key, params.get(key));
        }
        //创建Request....formBody...new formBody.Builder()...add()....build()
        Request request = new Request.Builder().url(url).post(builder.build()).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
    }
    /**
     * post请求上传文件....包括图片....流的形式传任意文件...
     * 参数1 url
     * file表示上传的文件
     * fileName....文件的名字,,例如aaa.jpg
     * params ....传递除了file文件 其他的参数放到map集合
     *
     */
    public static void uploadFile(String url, File file, String fileName,Map<String,String> params,
                          Callback callback) {
        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = getInstance();
        //MultipartBody多功能的请求实体对象,,,formBody只能传表单形式的数据
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        //参数
        if (params != null){
            for (String key : params.keySet()){
                builder.addFormDataPart(key,params.get(key));
            }
        }
        //文件...参数name指的是请求路径中所接受的参数...如果路径接收参数键值是fileeeee,此处应该改变
        builder.addFormDataPart("file",fileName, RequestBody.create(MediaType.parse("application/
                       octet-stream"),file));
        //构建
        MultipartBody multipartBody = builder.build();
        //创建Request
        Request request = new Request.Builder().url(url).post(multipartBody).build();
        //得到Call
        Call call = okHttpClient.newCall(request);
        //执行请求
        call.enqueue(callback);
    }
    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
     * 参数一:请求Url
     * 参数二:请求的JSON
     * 参数三:请求回调
     */
    public static void doPostJson(String url, String jsonParams, Callback callback) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; 
                            charset=utf-8"), jsonParams);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }
    /**
     * 下载文件 以流的形式把apk写入的指定文件 得到file后进行安装
     * 参数er:请求Url
     * 参数san:保存文件的文件夹....download
     */
    public static void download(final Activity context, final String url, final String saveDir) {
        Request request = new Request.Builder().url(url).build();
        Call call = getInstance().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //com.orhanobut.logger.Logger.e(e.getLocalizedMessage());
            }
            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();//以字节流的形式拿回响应实体内容
                    //apk保存路径
                    final String fileDir = isExistDir(saveDir);
                    //文件
                    File file = new File(fileDir, getNameFromUrl(url));
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(context, "下载成功:" + fileDir + "," + getNameFromUrl(url), 
                                       Toast.LENGTH_SHORT).show();
                        }
                    });
                    //apk下载完成后 调用系统的安装方法
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.
                                 package-archive");
                    context.startActivity(intent);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) is.close();
                    if (fos != null) fos.close();
                }
            }
        });
    }
    /**
     * 判断下载目录是否存在......并返回绝对路径
     *
     * @param saveDir
     * @return
     * @throws IOException
     */
    public static String isExistDir(String saveDir) throws IOException {
        // 下载位置
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
            if (!downloadFile.mkdirs()) {
                downloadFile.createNewFile();
            }
            String savePath = downloadFile.getAbsolutePath();
            Log.e("savePath", savePath);
            return savePath;
        }
        return null;
    }
    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */
    private static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }
}

RetrofitUtil

import android.util.Log;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitUtil {
    private static RetrofitUtil retrofitUtil = null;
    private Retrofit retrofit;

    private RetrofitUtil() {
    }

    private RetrofitUtil(String baseUrl) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new CommonParamsInterceptor())
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    public static RetrofitUtil getInstance(String baseUrl) {
        if (retrofitUtil == null) {
            synchronized (RetrofitUtil.class) {
                if (retrofitUtil == null) {
                    retrofitUtil = new RetrofitUtil(baseUrl);
                }
            }
        }
        return retrofitUtil;
    }

    public <T> T createService(Class<T> service) {
        return retrofit.create(service);
    }

    public static ApiService getService() {
        return RetrofitUtil.getInstance(Constant.BASE_URL).createService(ApiService.class);
    }

    private static class CommonParamsInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            String method = request.method();
            String oldUrl = request.url().toString();
            Log.e("----oldUrl",oldUrl);
            Map<String,String> map = new HashMap<>();
            map.put("source","android");
            if ("GET".equals(method)){
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(oldUrl);
                if (oldUrl.contains("?")){
                    if (oldUrl.indexOf("?") == oldUrl.length()-1){
                    }else {
                        stringBuilder.append("&");
                    }
                }else {
                    stringBuilder.append("?");
                }
                for (Map.Entry<String,String> entry: map.entrySet()) {
                    stringBuilder.append(entry.getKey())
                            .append("=")
                            .append(entry.getValue())
                            .append("&");
                }
                if (stringBuilder.indexOf("&") != -1){
                    stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&"));
                }
                String newUrl = stringBuilder.toString();
                Log.e("----newUrl",newUrl);
                request = request.newBuilder().url(newUrl).build();
            }else if ("POST".equals(method)){
                RequestBody requestBody = request.body();
                if (requestBody instanceof FormBody){
                    FormBody oldBody = (FormBody) requestBody;
                    FormBody.Builder builder = new FormBody.Builder();
                    for (int i = 0;i<oldBody.size();i++){
                        builder.add(oldBody.name(i),oldBody.value(i));
                    }
                    for (Map.Entry<String,String> entry: map.entrySet()) {
                        builder.add(entry.getKey(),entry.getValue());
                    }
                    request = request.newBuilder().url(oldUrl).post(builder.build()).build();
                }
            }
            Response response = chain.proceed(request);
            return response;
        }
    }
}

使用的依赖和方法

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.facebook.fresco:fresco:1.3.0'
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
compile 'io.reactivex.rxjava2:rxjava:2.1.6'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.squareup.okio:okio:1.13.0'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
compile 'io.reactivex.rxjava2:rxandroid:2.0.2'
compile 'com.jakewharton:butterknife:8.0.1'
compile 'com.github.bumptech.glide:glide:3.7.0'

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

bean文件夹下CountPriceBean

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;
    }
}

Select_Cart_Bean

import java.io.Serializable;
import java.util.List;

public class Select_Cart_Bean {

    private String code;
    private String msg;
    private List<DataBean> data;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {

        //自己手动创建一个变量 生成set get方法....记录组的checkBox是否选中
        private boolean isGroupChecked;

        public boolean isGroupChecked() {
            return isGroupChecked;
        }

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

        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 implements Serializable {

            private double bargainPrice;
            private String createtime;
            private String detailUrl;
            private String images;
            private int num;
            private int pid;
            private double price;
            private int pscid;
            private int selected;
            private int sellerid;
            private String subhead;
            private String title;

            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;
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值