购物车的简单实现

购物车页面的布局实现

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mcdull.fragment.SopCarFragment">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/sop_recyview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/sop_rlayout"/>
    <RelativeLayout
        android:id="@+id/sop_rlayout"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:background="#fff"
        android:layout_alignParentBottom="true">
        <CheckBox
            android:id="@+id/shop_checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="全选"
            android:layout_centerVertical="true"
            android:textSize="16sp"
            android:layout_marginLeft="20dp"/>
        <TextView
            android:id="@+id/sop_text_zj"
            android:layout_width="wrap_content"
            android:textSize="16sp"
            android:layout_height="wrap_content"
            android:text="合计:"
            android:layout_centerVertical="true"
            android:layout_marginLeft="120dp"/>
        <TextView
            android:id="@+id/shop_heji"
            android:layout_width="wrap_content"
            android:textSize="16sp"
            android:layout_height="wrap_content"
            android:text="0"
            android:textColor="#ff0000"
            android:layout_centerVertical="true"
            android:layout_marginLeft="170dp"/>
        <Button
            android:id="@+id/shop_jiesuan"
            android:layout_width="100dp"
            android:layout_height="match_parent"
            android:background="@color/colorAccent"
            android:layout_alignParentRight="true"
            android:text="去结算"/>
    </RelativeLayout>

</RelativeLayout>
//RecyclerView的条目布局

<?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="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/dp_20"
    android:paddingTop="@dimen/dp_10"
    xmlns:swipe="http://schemas.android.com/apk/res-auto">
    <CheckBox
        android:id="@+id/item_shopCat_check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/sp_12"
        android:layout_marginRight="@dimen/sp_12"/>

    <com.daimajia.swipe.SwipeLayout
        android:id="@+id/swipe"
        swipe:leftEdgeSwipeOffset="0dp"
        swipe:rightEdgeSwipeOffset="0dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="@dimen/dp_24">

        <LinearLayout
            android:background="@color/colorAccent"
            android:id="@+id/bottom_wrapper"
            android:layout_width="wrap_content"
            android:weightSum="1"
            android:layout_marginLeft="2dp"
            android:orientation="horizontal"
            android:layout_height="match_parent">
            <Button
                android:id="@+id/delete"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="删除"
                android:textColor="@android:color/white"
                android:background="@color/colorAccent"/>

        </LinearLayout>

        <RelativeLayout
            android:layout_width="@dimen/dp_292"
            android:layout_height="@dimen/dp_97"
            android:layout_marginRight="@dimen/dp_24">

            <com.facebook.drawee.view.SimpleDraweeView
                android:id="@+id/item_shopCat_img"
                android:layout_width="@dimen/dp_81"
                android:layout_height="@dimen/dp_81"
                android:layout_margin="@dimen/dp_8"/>

            <TextView
                android:id="@+id/item_shopCat_title"
                android:layout_width="match_parent"
                android:layout_height="@dimen/dp_60"
                android:layout_marginRight="@dimen/dp_8"
                android:layout_marginTop="@dimen/dp_8"
                android:textSize="@dimen/sp_12"
                android:layout_marginLeft="@dimen/dp_100"/>
            <TextView
                android:id="@+id/item_shopCat_price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="@dimen/dp_8"
                android:layout_marginTop="@dimen/dp_66"
                android:textSize="@dimen/sp_12"
                android:layout_marginLeft="@dimen/dp_100"
                android:textColor="@color/colorAccent"/>

            <com.mcdull.util.AddSubView
                android:id="@+id/item_shopCat_add"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/dp_50"
                android:layout_marginLeft="@dimen/dp_210"/>
        </RelativeLayout>
    </com.daimajia.swipe.SwipeLayout>
</LinearLayout>


//自定义加减器控件布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="@dimen/dp_70"
    android:layout_height="@dimen/dp_30"
    android:padding="2dp"
    android:layout_gravity="center_vertical"
    android:gravity="center_vertical">

    <TextView
        android:id="@+id/sub_jian"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:text="-"
        android:textSize="@dimen/sp_14"
        android:gravity="center"
        android:background="#fff"/>
    <TextView
        android:id="@+id/sub_num"
        android:layout_width="0dp"
        android:layout_weight="2"
        android:padding="@dimen/dp_2"
        android:layout_height="match_parent"
        android:text="1"
        android:textSize="@dimen/sp_12"
        android:gravity="center"
        android:background="#dddddd"/>
    <TextView
        android:id="@+id/sub_jia"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:text="+"
        android:textSize="@dimen/sp_14"
        android:gravity="center"
        android:background="#fff"/>
</LinearLayout>

 

//自定义控件的代码实现

public class AddSubView extends LinearLayout implements View.OnClickListener{

    public int number=1;
    private TextView mAdd;
    private TextView mSub;
    private TextView mNum;

    public interface OnNumberChangeListener{
        void onNumberChange(int number);
    }
    private OnNumberChangeListener onNumberChangeListener;
    public void setOnNumberChangeListener(OnNumberChangeListener onNumberChangeListener){
        this.onNumberChangeListener=onNumberChangeListener;
    }


    public AddSubView(Context context) {
        this(context,null);
    }

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

    public AddSubView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        View view = inflate(context, R.layout.add_remove, this);

        mAdd = view.findViewById(R.id.sub_jia);
        mSub = view.findViewById(R.id.sub_jian);
        mNum = view.findViewById(R.id.sub_num);
        mAdd.setOnClickListener(this);
        mSub.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.sub_jian:
                if (number>1){
                    number--;
                    mNum.setText(number+"");
                    if (onNumberChangeListener!=null){
                        onNumberChangeListener.onNumberChange(number);
                    }
                }else {
                    Toast.makeText(getContext(), "不能再少了", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.sub_jia:
                if (number<100){
                    number++;
                    mNum.setText(number+"");
                    if (onNumberChangeListener!=null){
                        onNumberChangeListener.onNumberChange(number);
                    }
                }else {
                    Toast.makeText(getContext(), "不能再多了", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    public int getNumber(){
        return number;
    }

    public void setNumber(int number){
        this.number=number;
        mNum.setText(number+"");
    }

}

//购物车适配器代码实现

public class ShopCatAdapter extends RecyclerView.Adapter<ShopCatAdapter.ViewHolder> {

    private Context mContext;
    private List<SopCar_Bean_Show.ResultBean> list;

    public ShopCatAdapter(Context context, List<SopCar_Bean_Show.ResultBean> list) {
        mContext = context;
        this.list = list;
    }
    public interface onItemClickListener {
        void onItemClick(int commodityId);

        void onCheckBoxClickListener(int position);

        void oJJChangeListener(int position, int number);

        void onBtnDelete(int layoutPosition);
    }

    private onItemClickListener onItemClickListener;

    public void setOnItemClickListener(onItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = View.inflate(mContext, R.layout.item_shopcat_show, null);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    public void deleteItem(int position) {
        list.remove(position);
        notifyItemRemoved(position);
    }
    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {

        holder.item_shopCat_title.setText(list.get(position).getCommodityName());
        holder.item_shopCat_price.setText("¥" + list.get(position).getPrice() + ".00");
        holder.item_shopCat_add.setNumber(list.get(position).getCount());
        holder.item_shopCat_check.setChecked(list.get(position).isCheck() == 1);
        Uri uri = Uri.parse(list.get(position).getPic());
        holder.item_shopCat_img.setImageURI(uri);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onItemClickListener != null) {
                    int commodityId = list.get(position).getCommodityId();
                    onItemClickListener.onItemClick(commodityId);
                }
            }
        });
        holder.item_shopCat_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    onItemClickListener.onCheckBoxClickListener(position);
            }
        });
        holder.item_shopCat_add.setOnNumberChangeListener(new AddSubView.OnNumberChangeListener() {
            @Override
            public void onNumberChange(int number) {
                    onItemClickListener.oJJChangeListener(position, number);

            }
        });
        holder.swipe.setShowMode(SwipeLayout.ShowMode.LayDown);
        holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int layoutPosition = holder.getLayoutPosition();

                    onItemClickListener.onBtnDelete(layoutPosition);

            }
        });
    }

    public void changeSp(int i) {
        list.get(i).setCheck(list.get(i).isCheck() == 0 ? 1 : 0);
    }

    public int getTotalPrice() {  //获取总价

        int totalPrice = 0;
        for (int x = 0; x < list.size(); x++) {
            if (list.get(x).isCheck() == 1) {
                int price = list.get(x).getPrice();
                int count = list.get(x).getCount();
                totalPrice += price * count;
            }
        }
        return totalPrice;
    }

    public void ChangeNumber(int i, int number) {
        list.get(i).setCount(number);
    }

    public Boolean getAllSpSelectState() {   //获取所有的商品选中状态
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isCheck() == 0) {
                return false;
            }
        }
        return true;
    }

    public Boolean getSpSelectIsSelected() {  //有一个商品选中则返回TRUE,表示可以去结算
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isCheck() == 1) {
                return true;
            }
        }
        return false;
    }

    public List<SopCar_Bean_Show.ResultBean> getSpSelectedData() {
        List<SopCar_Bean_Show.ResultBean> lists = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isCheck() == 1) {
                lists.add(list.get(i));
            }
        }
        return lists;
    }

    public void qxChangeAllSp(boolean isSelected) {       //全选改变商品是否选中
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setCheck(isSelected ? 1 : 0);

        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        public final CheckBox item_shopCat_check;
        public final SwipeLayout swipe;
        public final LinearLayout bottom_wrapper;
        public final Button delete;
        public final SimpleDraweeView item_shopCat_img;
        public final TextView item_shopCat_title;
        public final TextView item_shopCat_price;
        public final AddSubView item_shopCat_add;

        public ViewHolder(View itemView) {
            super(itemView);
            item_shopCat_check = itemView.findViewById(R.id.item_shopCat_check);
            swipe = itemView.findViewById(R.id.swipe);
            bottom_wrapper = itemView.findViewById(R.id.bottom_wrapper);
            delete = itemView.findViewById(R.id.delete);
            item_shopCat_img = itemView.findViewById(R.id.item_shopCat_img);
            item_shopCat_title = itemView.findViewById(R.id.item_shopCat_title);
            item_shopCat_price = itemView.findViewById(R.id.item_shopCat_price);
            item_shopCat_add = itemView.findViewById(R.id.item_shopCat_add);
        }
    }
}

//购物车页面逻辑实现

public class SopCarFragment extends BaseFragment implements SopCarView {

    private RecyclerView sop_recyview;
    private CheckBox shop_checkbox;
    private TextView sop_text_zj;
    private TextView shop_heji;
    private Button shop_jiesuan;
    private RelativeLayout sop_rlayout;
    private View mView;
    private SopCarPresenter mSopCarPresenter;
    private ArrayList<SopCar_Bean_Show.ResultBean> mSlist;
    private boolean isGetData = false;
    private String mSessionId;
    private String mUserId;
    private ShopCatAdapter mShopCatAdapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_sop_car, container, false);
        initView();
        initData();
        setListener();
        return mView;
    }

    @Override
    public void initView() {
        sop_recyview = (RecyclerView) mView.findViewById(R.id.sop_recyview);
        shop_checkbox = (CheckBox) mView.findViewById(R.id.shop_checkbox);
        sop_text_zj = (TextView) mView.findViewById(R.id.sop_text_zj);
        shop_heji = (TextView) mView.findViewById(R.id.shop_heji);
        shop_jiesuan = (Button) mView.findViewById(R.id.shop_jiesuan);
        sop_rlayout = (RelativeLayout) mView.findViewById(R.id.sop_rlayout);
        mSopCarPresenter = new SopCarPresenter();
        mSopCarPresenter.attach(this);
    }

    @Override
    public void initData() {
        mSlist = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        sop_recyview.setLayoutManager(linearLayoutManager);
        mShopCatAdapter = new ShopCatAdapter(getActivity(), mSlist);
        sop_recyview.setAdapter(mShopCatAdapter);
    }

    @Override
    public void setListener() {
        shop_checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Boolean allSpSelectState = mShopCatAdapter.getAllSpSelectState();
                mShopCatAdapter.qxChangeAllSp(!allSpSelectState);
                mShopCatAdapter.notifyDataSetChanged();
                refresh();
            }
        });
        mShopCatAdapter.setOnItemClickListener(new ShopCatAdapter.onItemClickListener() {
            @Override
            public void onItemClick(int commodityId) {

            }

            @Override
            public void onCheckBoxClickListener(int position) {
                mShopCatAdapter.changeSp(position);
                mShopCatAdapter.notifyDataSetChanged();
                refresh();
            }

            @Override
            public void oJJChangeListener(int position,int number) {
                mShopCatAdapter.ChangeNumber(position,number);
                mShopCatAdapter.notifyDataSetChanged();
                refresh();
            }

            @Override
            public void onBtnDelete(int layoutPosition) {
                mShopCatAdapter.deleteItem(layoutPosition);
                refresh();
            }
        });
        shop_jiesuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Boolean isSelected = mShopCatAdapter.getSpSelectIsSelected();
                if (isSelected){
                    Intent intent = new Intent(getActivity(),AffirmActivity.class);
                    List<SopCar_Bean_Show.ResultBean> spSelectedData = mShopCatAdapter.getSpSelectedData();
                    EventBus.getDefault().postSticky(spSelectedData);
                    Bundle bundle = new Bundle();
                    bundle.putString("mSessionId",mSessionId);
                    bundle.putString("mUserId",mUserId);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }else {
                    showHint("请选择商品");
                }
            }
        });
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void EventBusSticky(Login_EventBusStickyMessage login_eventBusStickyMessage) {
        mSessionId = login_eventBusStickyMessage.getSessionId();
        mUserId = login_eventBusStickyMessage.getUserId();
        mSopCarPresenter.PHeaderGet(mUserId, mSessionId);
    }
    private void refresh(){
        Boolean allSpSelectState = mShopCatAdapter.getAllSpSelectState();
        shop_checkbox.setChecked(allSpSelectState);
        int totalPrice = mShopCatAdapter.getTotalPrice();
        shop_heji.setText("¥:"+totalPrice+".00");
    }
    @Override
    public void QuerySopCarSuccess(List<SopCar_Bean_Show.ResultBean> list) {
        if (list != null) {
            mSlist.clear();
            mSlist.addAll(list);
            mShopCatAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void Failure(Exception e) {
        showHint(e + "");
    }
    @Override
    public void onResume() {
        if (!isGetData) {
            //切记只是进行数据请求与刷新而不是重新再设置一遍适配器
            mSopCarPresenter.PHeaderGet(mUserId, mSessionId);
            mShopCatAdapter.notifyDataSetChanged();
            isGetData = true;
        }
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mSopCarPresenter.detach();

    }

    @Override
    public void onPause() {
        super.onPause();
        isGetData = false;
    }

    /**
     * EventBus注册
     *
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    /**
     * 解除注册
     */
    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().removeAllStickyEvents();
        //解除注册
        EventBus.getDefault().unregister(this);
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值