Android_二级列表购物车之增删改查,全选反选,加减器,价钱数量计算

第一步: 导依赖

Eventbus依赖:

compile 'org.greenrobot:eventbus:3.1.1'
gson依赖:

compile 'com.google.code.gson:gson:2.8.2'

OkHttp依赖:

compile 'com.squareup.okhttp3:okhttp:3.9.0'
recyclerView依赖:

compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
glid依赖:

repositories {
  mavenCentral()
  maven { url 'https://maven.google.com' }
}

dependencies {
  compile 'com.github.bumptech.glide:glide:4.3.1'
  annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'
}
第二: 清单文件加权限:


    
    
    
第三:布局 Main_Activity



    

    

        

        

        

            


            


            
        
    





一级布局:




    

    

    


二级布局:




    

   
       
       
   


    

        
        
        
            

        

    

    

加减器布局:



    
第四:接口

public interface Callback {
    void onSuccess(String tag,Object o);
    void onFailure(String tag,Exception e);
}
public interface IView {
    void Success (String tag, List list);
    void Failed(String tag,Exception e);
}
第五: Okhttp

package com.bwei.www.yuekaomoni.okHttp;

import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.bwei.www.yuekaomoni.Callback.Callback;
import com.google.gson.Gson;

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

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @作者 
 * @时间 2017/11/18 10:34
 */

public class HttpUtils {
    private static final String TAG = "HttpUtils";
    private static volatile HttpUtils instanse;
    final static Handler handler = new Handler();

    private HttpUtils() {

    }
    public static HttpUtils getInstanse() {
        if (null == instanse) {
            synchronized (HttpUtils.class) {
                if (instanse == null) {
                    instanse = new HttpUtils();
                }
            }
        }
        return instanse;
    }
    public void get(String url, Map map, final Callback callBack,
                    final Class cls, final String tag) {
        // http://www.baoidu.com/login?mobile=11111&password=11111&age=1&name=zw

        // 1.http://www.baoidu.com/login                --------? key=value&key=value
        // 2.http://www.baoidu.com/login?               --------- key=value&key=value
        // 3.http://www.baoidu.com/login?mobile=11111   -----&key=value&key=value
        final StringBuffer sb = new StringBuffer();
        sb.append(url);

        if (TextUtils.isEmpty(url)) {
            return;
        }
        // 如果包含?说明是2.3类型
        if (url.contains("?")) {
            // 如果包含?并且?是最后一位,对应是2类型
            if (url.indexOf("?") == url.length() - 1) {

            } else {
                // 如果包含?并且?不是最后一位,对应是3类型
                sb.append("&");
            }
        }
        for (Map.Entry entry : map.entrySet()) {
            sb.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }
        if (sb.indexOf("&") != -1) {
            sb.deleteCharAt((sb.lastIndexOf("&")));
        }
        Log.i(TAG, "get:url " + sb.toString());
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = new Request.Builder()
                .get()
                .url(sb.toString())
                .build();
        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(tag,e);
                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String s = response.body().string();
                handler.post(new Runnable() {
                    Object o;
                    @Override
                    public void run() {
                        if(TextUtils.isEmpty(s)){
                            o=null;
                        }else
                        {
                            o = new Gson().fromJson(s, cls);
                        }
                        callBack.onSuccess(tag,o);
                    }
                });
            }
        });
    }
}
第六 :p层 {数据自己解析}

package com.bwei.www.yuekaomoni.present;

import com.bwei.www.yuekaomoni.Callback.Callback;
import com.bwei.www.yuekaomoni.Callback.IView;
import com.bwei.www.yuekaomoni.bean.GsonBean;
import com.bwei.www.yuekaomoni.okHttp.HttpUtils;

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

/**
 * @作者 
 * @时间 2017/11/18 10:51
 */

public class PresentCar {
    private IView inv;

    public void attachView(IView inv) {
        this.inv = inv;
    }
    public void getNews() {
        //type=top&key=dbedecbcd1899c9785b95cc2d17131c5
        Map map = new HashMap<>();

        HttpUtils.getInstanse().get("http://120.27.23.105/product/getCarts?uid=100", map, new Callback() {
            @Override
            public void onSuccess(String tag, Object o) {
                GsonBean bean = (GsonBean) o;
                if (bean != null) {
                    List data = bean.getData();

                    inv.Success(tag, data);
                }
            }

            @Override
            public void onFailure(String tag, Exception e) {
                inv.Failed(tag, e);
            }


        }, GsonBean.class, "news");
    }
    public void detachView() {
        if (inv != null) {
            inv = null;
        }
    }
}
第七:二级列表适配器:

package com.bwei.www.yuekaomoni.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bwei.www.yuekaomoni.R;
import com.bwei.www.yuekaomoni.bean.GsonBean;
import com.bwei.www.yuekaomoni.check.MessageEvent;
import com.bwei.www.yuekaomoni.eventbusevent.PriceAndCountEvent;
import com.bwei.www.yuekaomoni.myView.MyView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import static com.bwei.www.yuekaomoni.R.id.img;
import static com.bwei.www.yuekaomoni.R.id.mv;
import static com.bwei.www.yuekaomoni.R.id.tv_content;
import static com.bwei.www.yuekaomoni.R.id.tv_pri;

/**
 * @作者
 * @时间 2017/11/18 11:17
 */

public class StarExpanderAdapter extends BaseExpandableListAdapter {
    Context context;
    List dataBeen;
    ArrayList> listBean;



    public StarExpanderAdapter(Context context, List dataBeen, ArrayList> listBean) {
        this.context = context;
        this.dataBeen = dataBeen;
        this.listBean = listBean;

    }

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

    @Override
    public int getChildrenCount(int i) {
        return listBean.get(i).size();
    }

    @Override
    public Object getGroup(int i) {
            return dataBeen.get(i);
    }

    @Override
    public Object getChild(int i, int i1) {
        return listBean.get(i).get(i1);
    }

    @Override
    public long getGroupId(int i) {
        return i;
    }

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }
    //一级列表布局
    @Override
    public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
        final GsonBean.DataBean groupBean = dataBeen.get(i);
        final GroupViewHolder holder;
        if(view==null){
            holder = new GroupViewHolder();
            view = View.inflate(context, R.layout.gw_item2, null);
            holder.tv_sbt = view.findViewById(R.id.tv_sign);
            holder.cbgroup = view.findViewById(R.id.cb_parent);
            view.setTag(holder);
        }else
        {
            holder = (GroupViewHolder) view.getTag();
        }
        holder.cbgroup.setChecked(groupBean.isGropuCb());
        holder.tv_sbt.setText(groupBean.getSellerName());
        //一级列表checkBox的点击事件
        holder.cbgroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //判断一级列表复选框的状态  设置为true或false
                groupBean.setGropuCb(holder.cbgroup.isChecked());
                //改变二级checkbod的状态
                changeChildeCbState(i,holder.cbgroup.isChecked());
                //算钱
                EventBus.getDefault().post(compute());
                //改变全选状态   isAllGroupCbSelect判断一级是否全部选中
                changeAllCbState(isAllGroupCbSelected());
                //必刷新
                notifyDataSetChanged();
            }
        });
        return view;
    }
    //二级列表布局
    @Override
    public View getChildView(final int i, final int i1, boolean b, View view, ViewGroup viewGroup) {
        final GsonBean.DataBean.ListBean clildBean = this.listBean.get(i).get(i1);
        final ChildViewHolder childViewHolder;
        if(view==null){
           view = View.inflate(context, R.layout.gwc_item, null);
           childViewHolder = new ChildViewHolder();
            childViewHolder.tv_sbt = (TextView) view.findViewById(R.id.tv_sbt);
            childViewHolder.img = (ImageView) view.findViewById(img);
            childViewHolder.tv_pri = (TextView) view.findViewById(tv_pri);
            childViewHolder.tv_content = (TextView) view.findViewById(tv_content);
            childViewHolder.cbChild =view.findViewById(R.id.cb_child);
            childViewHolder.mv = view.findViewById(mv);
            childViewHolder.tv_del = view.findViewById(R.id.tv_del);
            childViewHolder.et_et = (EditText) childViewHolder.mv.findViewById(R.id.et_et);
            view.setTag(childViewHolder);
       }else{
            childViewHolder = (ChildViewHolder) view.getTag();
        }
        childViewHolder.tv_sbt.setText(clildBean.getTitle());
        String images = clildBean.getImages();
        String[] split = images.split("\\|");
        Glide.with(context).load(split[0]).into(childViewHolder.img);
        childViewHolder.tv_pri.setText(clildBean.getPrice()+"");
        childViewHolder.tv_content.setText(clildBean.getSubhead());
        childViewHolder.cbChild.setChecked(clildBean.isChildCb());
        childViewHolder.et_et.setText(clildBean.getNum()+"");
        //加号
        childViewHolder.mv.setOnAddDelClickLstener(new MyView.OnAddDelClickLstener() {
            @Override
            public void onAddClick(View v) {
                int num = clildBean.getNum();
                //num为int类型所以要加空字符串
                childViewHolder.et_et.setText(++num+"");
                clildBean.setNum(num);
                //如果二级列表的checkbox为选中,计算价钱
                if (childViewHolder.cbChild.isChecked()){
                    PriceAndCountEvent priceAndCountEvent = compute();
                    EventBus.getDefault().post(priceAndCountEvent);
                }
            }
        //减号
            @Override
            public void onDelClick(View v) {
                int num = clildBean.getNum();
                if(num==1){
                    return;
                }
                childViewHolder.et_et.setText(--num+"");
                clildBean.setNum(num);
                if(childViewHolder.cbChild.isChecked()){
                    PriceAndCountEvent priceAndCountEvent = compute();
                    EventBus.getDefault().post(priceAndCountEvent);
                }
            }
        });
        //删除
        childViewHolder.tv_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List listBeen = listBean.get(i);
                GsonBean.DataBean.ListBean remove = listBeen.remove(i1);
                if(listBeen.size()==0){
                    //先移除二级列表的集合,再移除一级列表的集合
                    listBean.remove(i);
                    dataBeen.remove(i);
                }
                //算钱
                EventBus.getDefault().post(compute());
                notifyDataSetChanged();
            }
        });

        //二级列表的点击事件
        childViewHolder.cbChild.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //设置该条目对象里的checked属性值
                clildBean.setChildCb(childViewHolder.cbChild.isChecked());
                //计算价钱
                PriceAndCountEvent priceAndCountEvent = compute();
                EventBus.getDefault().post(priceAndCountEvent);
                //判断当前checkbox是选中的状态
                if(childViewHolder.cbChild.isChecked()){
                    //如果全部选中(isAllChildCbSelected)
                    if(isAllChildCbSelected(i)){
                        //改变一级列表的状态
                        changGroupCbState(i,true);
                        //改变全选的状态
                        changeAllCbState(isAllGroupCbSelected());
                    }
                }else {
                    //如果没有全部选中,一级列表的checkbox为false不为选中
                    changGroupCbState(i,false);
                    changeAllCbState(isAllGroupCbSelected());
                }
                notifyDataSetChanged();
            }
        });

        return view;
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }
    class GroupViewHolder {
        CheckBox cbgroup;
        TextView tv_sbt;
    }
    class ChildViewHolder {
        TextView tv_sbt;
        ImageView img;
        TextView tv_pri;
        TextView tv_content;
        CheckBox cbChild;
        MyView mv;
        TextView tv_del;

        EditText et_et;
    }

    /**
     * 改变二级列表checkbox状态
     * 如果一级选中,控制二级也选中
     * @param i
     * @param flag
     */
     private void changeChildeCbState(int i,boolean flag){
         List listBeen = listBean.get(i);
         for (int j = 0; j  listBeen = listBean.get(i);
         for (int j = 0; j  listBeen = listBean.get(i);
         for (int j = 0; j  listBeen = listBean.get(i);
             for (int j = 0; j 
第八:MessageEvent类:
public class MessageEvent {
    private boolean checked;

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }
}
  PriceAndCountEvent 类:
public class PriceAndCountEvent {
    private int price;
    private int count;

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getCount() {
        return count;
    }

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


第九:
MainActivity:
package com.bwei.www.yuekaomoni;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.bwei.www.yuekaomoni.Callback.IView;
import com.bwei.www.yuekaomoni.adapter.StarExpanderAdapter;
import com.bwei.www.yuekaomoni.bean.GsonBean;
import com.bwei.www.yuekaomoni.eventbusevent.MessageEvent;
import com.bwei.www.yuekaomoni.eventbusevent.PriceAndCountEvent;
import com.bwei.www.yuekaomoni.present.PresentCar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

public class Main2Activity extends AppCompatActivity implements IView {

    private ExpandableListView elv;
    ArrayList dataBeen = new ArrayList<>();
    private CheckBox checkquan;
    private List lists;
    ArrayList> listBean = new ArrayList<>();
    private StarExpanderAdapter adapter;
    private TextView tv_price;
    private TextView tv_num;
    private PresentCar presentCar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        //注册一下
        EventBus.getDefault().register(this);
        //获取控件
        elv = (ExpandableListView) findViewById(R.id.elv);
        checkquan = (CheckBox) findViewById(R.id.checkbox2);
        tv_price = (TextView) findViewById(R.id.tv_price);
        tv_num = (TextView) findViewById(R.id.tv_num);
        //获取数据
        presentCar = new PresentCar();
        presentCar.attachView(this);
        presentCar.getNews();
        checkquan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //设置全选
                adapter.changeAllListCbState(checkquan.isChecked());
            }
        });

    }
    //销毁方法
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //eventBus销毁
        EventBus.getDefault().unregister(this);
        if (presentCar!=null){
            presentCar.detachView();
        }

    }
    @Override
    public void Success(String tag, List list) {
       dataBeen.addAll(list);
        for (int i = 0; i < dataBeen.size(); i++) {
            GsonBean.DataBean bean = dataBeen.get(i);
            lists = bean.getList();
            listBean.add(lists);
        }


        adapter = new StarExpanderAdapter(Main2Activity.this,dataBeen,listBean);
        elv.setAdapter(adapter);
        //隐藏二级列表前小三角
        elv.setGroupIndicator(null);
        //使二级列表一直展示
        for (int i = 0; i 
还有一个 自定义View:

package com.bwei.www.yuekaomoni.myView;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.bwei.www.yuekaomoni.R;

/**
 * @作者 
 * @时间 2017/11/18 09:56
 */

public class MyView extends LinearLayout{
    private OnAddDelClickLstener lister;
    private Button btn_add;
    private Button txtAdd;
    private EditText et_et;
    private Button btn_del;

    //定义一个对外开放的接口
    public interface OnAddDelClickLstener{
        void onAddClick(View v);
        void onDelClick(View v);
    }
    public void setOnAddDelClickLstener(OnAddDelClickLstener lister){
        if(lister!=null){
            this.lister = lister;
        }
    }
    public MyView(Context context) {
        this(context,null);
    }

    public MyView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs, defStyleAttr);
    }

    private void initView(Context context, AttributeSet attrs, int defStyleAttr) {
        View.inflate(context, R.layout.myview,this);
        btn_add = (Button) findViewById(R.id.btn_add);
        btn_del = (Button) findViewById(R.id.btn_del);
        et_et = (EditText) findViewById(R.id.et_et);

        btn_del.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("AddDeleteView","点击了减号");
                lister.onDelClick(view);
            }
        });
        btn_add.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("txtAdd","点击了加号");
                lister.onAddClick(view);
            }
        });

    }


}














你可能感兴趣的:(Android_二级列表购物车之增删改查,全选反选,加减器,价钱数量计算)