1. 程式人生 > >Android_二級列表購物車之增刪改查,全選反選,加減器,價錢數量計算

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'
}
第二: 清單檔案加許可權:
<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
第三:佈局 Main_Activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"

    tools:context="com.bwei.www.yuekaomoni.Main2Activity">
    <ExpandableListView
        android:id="@+id/elv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:background="@android:color/white"
        android:gravity="center_vertical">

        <CheckBox
            android:id="@+id/checkbox2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:focusable="false" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@+id/checkbox2"
            android:gravity="center_vertical"
            android:text="全選"
            android:textSize="20sp" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="100dp"
            android:orientation="horizontal">

            <TextView

                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="合計 :" />


            <TextView
                android:id="@+id/tv_price"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:layout_marginLeft="10dp"
                android:paddingRight="10dp"
                android:text="0"
                android:textColor="@android:color/holo_red_light" />


            <TextView
                android:layout_marginLeft="150dp"
                android:id="@+id/tv_num"
                android:layout_width="150dp"
                android:layout_height="50dp"
                android:background="@android:color/holo_red_dark"
                android:gravity="center"
                android:padding="10dp"
                android:text="結算(0)"
                android:textColor="@android:color/white" />
        </LinearLayout>
    </RelativeLayout>




</LinearLayout>
一級佈局:
<?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="10dp"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <CheckBox
        android:id="@+id/cb_parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp"
        android:focusable="false" />

    <TextView
        android:id="@+id/tv_sign"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="標記" />

    <TextView
        android:id="@+id/tv_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="12345678" />

</LinearLayout>
二級佈局:
<?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_vertical"
    android:orientation="horizontal">

    <CheckBox
        android:id="@+id/cb_child"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="30dp"
        android:focusable="false" />

   <RelativeLayout
       android:layout_width="100dp"
       android:layout_height="100dp"
       >
       <TextView
           android:id="@+id/tv_sbt"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:singleLine="true"
           android:ellipsize="end"
           android:text="三隻松鼠大禮包發動機"/>
       <ImageView
           android:layout_below="@id/tv_sbt"
           android:layout_width="80dp"
           android:layout_height="80dp"
           android:id="@+id/img"
           android:src="@mipmap/ic_launcher"/>
   </RelativeLayout>


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

        <TextView
            android:id="@+id/tv_pri"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:text="¥3000.00" />
        <TextView
            android:id="@+id/tv_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:text="什麼" />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical">
            <com.bwei.www.yuekaomoni.myView.MyView
                android:id="@+id/mv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"></com.bwei.www.yuekaomoni.myView.MyView>

        </LinearLayout>

    </LinearLayout>

    <Button
        android:id="@+id/tv_del"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:background="@drawable/rublish"
         />
</LinearLayout>

加減器佈局:

<?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">
    <Button
        android:id="@+id/btn_add"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:background="@drawable/shopcart_add_red"/>
    <EditText
        android:id="@+id/et_et"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:text="1"
        android:textSize="20dp"/>
    <Button
        android:id="@+id/btn_del"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:background="@drawable/shopcart_minus_red"/>
</LinearLayout>
第四:介面
public interface Callback {
    void onSuccess(String tag,Object o);
    void onFailure(String tag,Exception e);
}
public interface IView {
    void Success (String tag, List<GsonBean.DataBean> 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<String, String> 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<String, String> 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<String, String> 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<GsonBean.DataBean> 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<GsonBean.DataBean> dataBeen;
    ArrayList<List<GsonBean.DataBean.ListBean>> listBean;



    public StarExpanderAdapter(Context context, List<GsonBean.DataBean> dataBeen, ArrayList<List<GsonBean.DataBean.ListBean>> 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<GsonBean.DataBean.ListBean> 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<GsonBean.DataBean.ListBean> listBeen = listBean.get(i);
         for (int j = 0; j <listBeen.size(); j++) {
             GsonBean.DataBean.ListBean listBean = listBeen.get(j);
             listBean.setChildCb(flag);
         }
     }

    /**
     * 判斷一級列表是否全選中
     * @return
     */
     private boolean isAllGroupCbSelected(){
         for (int i = 0; i <dataBeen.size() ; i++) {
             GsonBean.DataBean dataBean = dataBeen.get(i);
             if(!dataBean.isGropuCb()){
                 return false;
             }
         }
         return true;
     }
    /**
     * 改變全選的狀態
     *
     * @param flag
     */
     private void changeAllCbState(boolean flag){
         MessageEvent messageEvent = new MessageEvent();
         messageEvent.setChecked(flag);
         EventBus.getDefault().post(messageEvent);
     }

    /**
     * 判斷二級列表是否全部選中
     * @param i
     * @return
     */
    private boolean isAllChildCbSelected (int i){
         List<GsonBean.DataBean.ListBean> listBeen = listBean.get(i);
         for (int j = 0; j <listBeen.size() ; j++) {
             GsonBean.DataBean.ListBean listBean = listBeen.get(j);
             if(!listBean.isChildCb()){
                 return false;
             }
         }
         return true;
     }
    /**
     * 改變一級列表checkbox狀態
     *
     * @param i
     */
     private void changGroupCbState(int i,boolean flag){
         GsonBean.DataBean dataBean = dataBeen.get(i);
         dataBean.setGropuCb(flag);
     }

    /**
     * 改變二級列表checkbox狀態
     * @param i
     * @param flag
     */
     private void changeChildCbState(int i,boolean flag){
         List<GsonBean.DataBean.ListBean> listBeen = listBean.get(i);
         for (int j = 0; j <listBeen.size() ; j++) {
             GsonBean.DataBean.ListBean listBean = listBeen.get(j);
             listBean.setChildCb(flag);
         }
     }
    /**
     * 計算列表中,選中的錢和數量
     */
     private PriceAndCountEvent compute(){
        int count = 0;
         int price = 0;
         for (int i = 0; i <listBean.size() ; i++) {
             List<GsonBean.DataBean.ListBean> listBeen = listBean.get(i);
             for (int j = 0; j <listBeen.size() ; j++) {
                 GsonBean.DataBean.ListBean listBean = listBeen.get(j);
                 if(listBean.isChildCb()){
                     price+=listBean.getNum()*listBean.getPrice();
                     count+=listBean.getNum();
                 }
             }
         }
         PriceAndCountEvent priceAndCountEvent = new PriceAndCountEvent();
         priceAndCountEvent.setCount(count);
         priceAndCountEvent.setPrice(price);
         return priceAndCountEvent;
     }
    /**
     * 設定全選、反選
     *
     * @param flag
     */
    public void changeAllListCbState(boolean flag) {
        for (int i = 0; i < dataBeen.size(); i++) {
            changGroupCbState(i, flag);
            changeChildCbState(i, flag);
        }
        //算錢
        EventBus.getDefault().post(compute());
        notifyDataSetChanged();
    }

}
第八: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<GsonBean.DataBean> dataBeen = new ArrayList<>();
    private CheckBox checkquan;
    private List<GsonBean.DataBean.ListBean> lists;
    ArrayList<List<GsonBean.DataBean.ListBean>> 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<GsonBean.DataBean> 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 <dataBeen.size() ; i++) {
            elv.expandGroup(i);
        }

    }

    @Override
    public void Failed(String tag, Exception e) {

    }
    //必寫註解
    @Subscribe
    public void onMessageEvent(MessageEvent event) {
        checkquan.setChecked(event.isChecked());
    }

    @Subscribe
    public void onMessageEvent(PriceAndCountEvent event) {
        tv_num.setText("結算(" + event.getCount() + ")");
        tv_price.setText(event.getPrice() + "");
    }
}
還有一個 自定義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_二級列表購物車刪改,,,價錢數量計算

第一步: 導依賴 Eventbus依賴: compile 'org.greenrobot:eventbus:3.1.1'gson依賴: compile 'com.google.code.gson:gson:2.8.2' OkHttp依賴: compile 'com.squa

Asp.Net MVC EF-DbFirst刪改

生成 處的 message mod 更新 get請求 layout 失敗 inf 控制器及動作方法: using System; using System.Collections.Generic; using System.Linq; using System.Web;

MongoDB刪改(一)

type over friend top ews tex 內容 ive review 本文主要介紹MongoDB數據庫增刪改查操作。 增 mongoDB和其它關系型數據庫一樣,通過insert來添加數據到集合中去。 db.collectio

MySQL刪改

語法 執行 ted 結束 trunc 長度 第一條 顯示 str 前言:以下是MySQL最基本的增刪改查語句,很多IT工作者都必須要會的命令,也是IT行業面試最常考的知識點,由於是入門級基礎命令,所有所有操作都建立在單表上,未涉及多表操作。 前提:在進行“增刪改查”的操

Mysql常用命令操作刪改

賬號 建立 批量插入 創建表 tab use 常用命令 default images 1.數據庫操作: 1.1 創建數據庫 : create database <數據庫名> a.建立一個名為oldboy_default的數據

Python學習路:文件操作刪改

打印 odin day 打開 aps 之前 編碼 數據 adl f = open("yesterday","r",encoding="utf-8") #print(f.read()) #for i in range(5): # print(f.readline())

mysql基本操作刪改

mysql查詢查詢所有列select * from 表名;例:select * from classes;查詢指定列可以使用as為列或表指定別名select 列1,列2,... from 表名;例:select id,name from classes;增加說明:主鍵列是自動增長,但是在全列插入時需要占位,通

模擬admin組件自己開發stark組件刪改

.html del delet inpu render .site itl filter ext 增刪改查,針對視圖 我們需要modelform來創建,可自動生成標簽,我們還要考慮用戶是不是自己定制,依然解決方法是,繼承和重寫 app01下的joker.py文件 clas

bootstrap刪改

ali odata .html 顯示 return style pagelist CA null 後臺使用spring boot和spring cloud等。前端使用bootstrap框架進行基本操作,項目采用前後端分離。 1、查詢 <!-- HTML中代碼 此中

Mybatis入門案例刪改

取值 private wid resources property 文件 3.0 AS 普通 MyBatis:是一個支持普通sql查詢和存儲過程以及高級映射的優秀持久層框架,其主要思想是將代碼中大量的SQL語句剝離出來,配置到配置文件中,以實現SQL的靈活配置. mybat

Flask中數據庫框架和模型類四:再述SQLAlchemy配置和基本操作刪改

模糊 offset odi com app ack 字符 add () from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) #設置連接數據庫的URL

django08 orm刪改

day68 2018-05-10 來老男孩教育學習必經的四個階段: 第一個階段:信心滿滿(我一定能學會,我為啥學不會) 第二個階段:自我懷疑(臥槽!還真不好學!) 第三個階段:極其浮躁(臥槽!怎麼還不畢業!這講師連Django都講不明白!) 第四個階段:極其焦慮(臥槽!怎麼要畢業了?我什麼都不會,怎麼找工作

PHP程式碼刪改

新增資料(重點) 用PDO類中的exec方法來執行insert語句,成功返回受影響的行數,失敗返回false。 exec是單詞execute的簡寫。執行的意思。 刪除和修改資料(重點) 仍然使用的是PDO類中的exec方法。成功返回受影響的行數,失敗返回false。

2——列表型別(刪改

列表(list) 增 在列表中逗號後面加空格! append()(追加):預設在列表末尾新增元素(id不變); li = [1, 2, 3, 4] >>>li.append(5) >>>li >>>[1, 2, 3, 4, 5] ins

laravel 框架刪改

  需要引用檔案 namespace App\Http\Controllers\Yicontroller; use Illuminate\Http\Request; use App\Http\Controllers\Controller; //因為需要引用DB方法 所以需要

MongoDB 刪改

對於mongodb,使用了不存在的物件,就等於在建立這個物件 一, 建立資料庫   注意:操作資料庫的方式:db.表名(Collections).操作(引數) 二,增 插入資料(insert     insertOne     insertMan

jmeter連接數據庫刪改

inf ima nbsp 分享 增刪 image 插入 jmeter 分享圖片 配置jdbc: 查詢sql配置: 插入sql配置: 修改sql配置: 刪除sql配置: jmeter連接數據庫之增刪改查

day79_淘淘商城專案_12_購物車流程 + 商城購物車系統的搭建 + 商城購物車系統的實現分析 + 購物車實現刪改_匠心筆記

課程計劃 1、購物車的流程 2、購物車的實現 a) 登入狀態下的購物車實現 b) 未登入狀態下的購物車實現 1、購物車流程 1.1、以前的購物車流程 使用者將商品新增到購物車時,判斷使用者是否登入,如果已經登入將購物車放入se

JDBC刪改

一、什麼是JDBC JDBC(Java DataBase Connectivity)就是Java資料庫連線,用Java語言來操作資料庫。簡單地說,JDBC就是用於執行SQL語句的一系列Java API。 二、為什麼要使用JDBC 早期SUN公司想編寫一套可以連線天下所有資料庫的