1. 程式人生 > >商品詳情介面點選跳轉到購物車(二)購物車介面

商品詳情介面點選跳轉到購物車(二)購物車介面

//佈局檔案

<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.example.gaochao.shopcartdemo1.ShopCartActivity">

    <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="40dp">

        <CheckBox
            android:id="@+id/cb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="全選" />

        <TextView
            android:id="@+id/tvTotal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="15dp"
            android:layout_toRightOf="@id/cb"
            android:text="合計:" />

        <TextView
            android:id="@+id/tvCount"
            android:layout_width="100dp"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:background="#ff0000"
            android:gravity="center"
            android:text="去結算(0)"
            android:textColor="#ffffff" />
    </RelativeLayout>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <CheckBox
        android:id="@+id/cbGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tvGroup"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center_vertical" />

</LinearLayout>
<LinearLayout
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <CheckBox
        android:id="@+id/cbChild"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/iv"
        android:layout_width="100dp"
        android:layout_height="100dp" />

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

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



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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal">

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

            <ImageView
                android:layout_marginLeft="10dp"
                android:id="@+id/ivDel"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:background="@drawable/iv_del" />

            <TextView
                android:id="@+id/tvNum"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="25sp"
                android:layout_marginLeft="3dp"
                android:layout_marginRight="3dp"
                android:text="1"/>

            <ImageView
                android:id="@+id/ivAdd"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:background="@drawable/iv_add" />
        </LinearLayout>
    </LinearLayout>
    <Button
        android:id="@+id/btDel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="刪除" />
</LinearLayout>

//封裝  兩個bean   購物車商品介面bean    提取總價和結算總價   ShopCarBean  priceAndCount

ShopCartBean
PriceAndCount

//m層

public interface ShopCartModelListener {
    void getCart(Map<String,String> params, OnNetListener<ShopCartBean> bean);
}

public class ShopCartModel implements ShopCartModelListener {
    private Handler handler = new Handler();
    @Override
    public void getCart(Map<String, String> params, final OnNetListener<ShopCartBean> onNetListener) {
        OkHttpUtils.getOkHttpUtils().doPost(API.str2, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                final ShopCartBean shopCartBean = new Gson().fromJson(string, ShopCartBean.class);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onNetListener.onSuccess(shopCartBean);
                    }
                });
            }
        });
    }
}
//p層
public class ShopCartPresenter {

    private ShopCartViewListener shopCartViewListener;
    private ShopCartModelListener shopCartModelListener;
    public ShopCartPresenter(ShopCartViewListener shopCartViewListener) {
        this.shopCartViewListener = shopCartViewListener;
        shopCartModelListener = new ShopCartModel();
    }
    public void onDettach(){
        shopCartViewListener=null;
    }
    public void getShaopCartData(){
        Map<String,String> params = new HashMap<>();
        params.put("uid","1234");
        params.put("pid","71");
        shopCartModelListener.getCart(params, new OnNetListener<ShopCartBean>() {
            @Override
            public void onSuccess(ShopCartBean shopCartBean) {
                if (shopCartViewListener != null){
                    List<ShopCartBean.DataBean> group = shopCartBean.getData();
                    List<List<ShopCartBean.DataBean.ListBean>> child = new ArrayList<>();

                    for (int i=0;i<group.size();i++){
                        child.add(group.get(i).getList());
                    }
                    shopCartViewListener.show(group,child);
                }
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }
}

//v層

public interface ShopCartViewListener {
    void show(List<ShopCartBean.DataBean> group,List<List<ShopCartBean.DataBean.ListBean>> child);
}

public class ShopCartActivity extends AppCompatActivity implements ShopCartViewListener {

    private ShopCartPresenter getCartPresenter;
    private ExpandableListView mElv;
    /**
     * 全選
     */
    private CheckBox mCb;
    /**
     * 合計:
     */
    private TextView mTvTotal;
    /**
     * 去結算(0)
     */
    private TextView mTvCount;
    private ElcAdapter elvAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_cart);
        initView();
        getCartPresenter = new ShopCartPresenter(this);
        getCartPresenter.getShaopCartData();

        mCb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                elvAdapter.AllOrNone(mCb.isChecked());
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getCartPresenter.onDettach();
    }

    @Override
    public void show(List<ShopCartBean.DataBean> group, List<List<ShopCartBean.DataBean.ListBean>> child) {
        elvAdapter = new ElcAdapter(this, group, child);
        mElv.setGroupIndicator(null);
        mElv.setAdapter(elvAdapter);
        for (int i = 0; i < group.size(); i++) {
            mElv.expandGroup(i);

        }
    }

    private void initView() {
        mElv = (ExpandableListView) findViewById(R.id.elv);
        mCb = (CheckBox) findViewById(R.id.cb);
        mTvTotal = (TextView) findViewById(R.id.tvTotal);
        mTvCount = (TextView) findViewById(R.id.tvCount);
    }

    public void setPriceAndCount(PriceAndCount priceAndCount) {
        mTvTotal.setText("合計:" + priceAndCount.getPrice());
        mTvCount.setText("去結算(" + priceAndCount.getCount() + ")");
    }

    public void setAllChecked(boolean bool) {
        mCb.setChecked(bool);
    }
}

//介面卡
class ElcAdapter extends BaseExpandableListAdapter{
    private Context context;
    private List<ShopCartBean.DataBean> group;
    private List<List<ShopCartBean.DataBean.ListBean>> child;
    private final LayoutInflater inflater;

    public ElcAdapter(Context context, List<ShopCartBean.DataBean> group, List<List<ShopCartBean.DataBean.ListBean>> child) {
        this.context = context;
        this.group = group;
        this.child = child;
        inflater = LayoutInflater.from(context);
    }

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

    @Override
    public int getChildrenCount(int groupPosition) {
        return child.get(groupPosition).size();
    }

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

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return child.get(groupPosition).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 false;
    }

    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        View view;
        final GroupViewHolder holder;
        if (convertView == null) {
            view = inflater.inflate(R.layout.group_item1, null);
            holder = new GroupViewHolder();
            holder.tv = view.findViewById(R.id.tvGroup);
            holder.cbGroup = view.findViewById(R.id.cbGroup);
            view.setTag(holder);
        } else {
            view = convertView;
            holder = (GroupViewHolder) view.getTag();
        }
        final ShopCartBean.DataBean dataBean = group.get(groupPosition);
        holder.tv.setText(dataBean.getSellerName());
        holder.cbGroup.setChecked(dataBean.isChecked());

        holder.cbGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //需要改變三個checkbox的狀態值
                //1.一級列表的checkbox狀態值
                dataBean.setChecked(holder.cbGroup.isChecked());
                //2.二級列表的checkbox狀態值
                setChildrenCb(groupPosition, holder.cbGroup.isChecked());
                //3.全選的checkbox狀態值
                ((ShopCartActivity) context).setAllChecked(isAllGroupCbChecked());
                //計算錢和數量並顯示
                setPriceAndCount();
                //重新整理介面
                notifyDataSetChanged();
            }
        });
        return view;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, final View convertView, ViewGroup parent) {
        View view;
        final ChildViewHolder holder;
        if (convertView == null) {
            view = inflater.inflate(R.layout.child_item2, null);
            holder = new ChildViewHolder();
            holder.iv = view.findViewById(R.id.iv);
            holder.tvTitle = view.findViewById(R.id.tvTitle);
            holder.tvSubhead = view.findViewById(R.id.tvSubhead);
            holder.tvPrice = view.findViewById(R.id.tvPrice);
            holder.cbChild = view.findViewById(R.id.cbChild);
            holder.btDel = view.findViewById(R.id.btDel);
            holder.tvNum = view.findViewById(R.id.tvNum);
            holder.ivDel = view.findViewById(R.id.ivDel);
            holder.ivAdd = view.findViewById(R.id.ivAdd);
            view.setTag(holder);
        } else {
            view = convertView;
            holder = (ChildViewHolder) view.getTag();
        }

        final ShopCartBean.DataBean.ListBean listBean = child.get(groupPosition).get(childPosition);
        String images = listBean.getImages();
        Glide.with(context).load(images.split("\\|")[0]).into(holder.iv);
        holder.tvTitle.setText(listBean.getTitle());
        holder.cbChild.setChecked(child.get(groupPosition).get(childPosition).isChecked());
        holder.tvSubhead.setText(listBean.getSubhead());
        holder.tvPrice.setText(listBean.getPrice() + "元");
        holder.tvNum.setText(listBean.getCount() + "");
        //給checkbox設定點選事件
        holder.cbChild.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //需要改變三個checkbox的狀態值
                //1.二級列表的checkbox狀態值
                listBean.setChecked(holder.cbChild.isChecked());
                //2.一級列表的checkbox狀態值
                group.get(groupPosition).setChecked(isAllChildCbChecked(groupPosition));
                //3.全選的checkbox狀態值
                ((ShopCartActivity) context).setAllChecked(isAllGroupCbChecked());
                //計算錢和數量並顯示
                setPriceAndCount();
                //重新整理介面
                notifyDataSetChanged();
            }
        });

        holder.ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //獲取目前顯示的值
                int count = listBean.getCount();
                count++;
                //改變JavaBean裡的狀態值
                listBean.setCount(count);
                //計算錢和數量並顯示
                setPriceAndCount();
                //重新整理列表
                notifyDataSetChanged();
            }
        });
        holder.ivDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //獲取目前顯示的值
                int count = listBean.getCount();
                if (count <= 1) {
                    count = 1;
                } else {
                    count--;
                }
                //改變JavaBean裡的狀態值
                listBean.setCount(count);
                //計算錢和數量並顯示
                setPriceAndCount();
                //重新整理列表
                notifyDataSetChanged();
            }
        });

        holder.btDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //其實就是刪除集合
                List<ShopCartBean.DataBean.ListBean> listBeans = child.get(groupPosition);
                if (listBeans.size() > 0) {
                    listBeans.remove(childPosition);
                }
                if (listBeans.size() == 0) {
                    child.remove(groupPosition);
                    group.remove(groupPosition);
                }
                //計算錢和數量並顯示
                setPriceAndCount();
                //改變全選狀態
                ((ShopCartActivity) context).setAllChecked(isAllGroupCbChecked());
                //重新整理列表
                notifyDataSetChanged();
            }
        });
        return view;
    }

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

    class GroupViewHolder {
        TextView tv;
        CheckBox cbGroup;
    }

    class ChildViewHolder {
        ImageView iv;
        TextView tvTitle;
        TextView tvSubhead;
        TextView tvPrice;
        CheckBox cbChild;
        Button btDel;
        TextView tvNum;
        ImageView ivDel;
        ImageView ivAdd;
    }

    /**
     * 設定一級列表對應的二級列表checkbox狀態
     *
     * @param groupPosition
     * @param bool
     */
    private void setChildrenCb(int groupPosition, boolean bool) {
        List<ShopCartBean.DataBean.ListBean> listBeans = child.get(groupPosition);
        for (int i = 0; i < listBeans.size(); i++) {
            listBeans.get(i).setChecked(bool);
        }
    }

    /**
     * 判斷一級列表checkbox狀態
     *
     * @return
     */
    private boolean isAllGroupCbChecked() {
        if (group.size() == 0) {
            return false;
        }
        for (int i = 0; i < group.size(); i++) {
            if (!group.get(i).isChecked()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判斷二級列表checkbox狀態
     *
     * @return
     */
    private boolean isAllChildCbChecked(int groupPosition) {
        List<ShopCartBean.DataBean.ListBean> listBeans = child.get(groupPosition);
        for (int i = 0; i < listBeans.size(); i++) {
            if (!listBeans.get(i).isChecked()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 設定錢和數量
     */
    private void setPriceAndCount() {
        ((ShopCartActivity) context).setPriceAndCount(compute());
    }

    /**
     * 計算錢和數量
     */
    private PriceAndCount compute() {
        double price = 0;
        int count = 0;
        for (int i = 0; i < group.size(); i++) {
            List<ShopCartBean.DataBean.ListBean> listBeans = child.get(i);
            for (int j = 0; j < listBeans.size(); j++) {
                if (listBeans.get(j).isChecked()) {
                    price += listBeans.get(j).getPrice() * listBeans.get(j).getCount();
                    count += listBeans.get(j).getCount();
                }
            }
        }
        return new PriceAndCount(price, count);
    }

    /**
     * 全選或者全不選
     *
     * @param bool
     */
    public void AllOrNone(boolean bool) {
        for (int i = 0; i < group.size(); i++) {
            group.get(i).setChecked(bool);
            setChildrenCb(i, bool);
        }
        setPriceAndCount();
        notifyDataSetChanged();
    }
}