其他分享
首页 > 其他分享> > 购物车的基本代码 不完善

购物车的基本代码 不完善

作者:互联网

//自定义加减器
public class SubAddButton extends LinearLayout {

private View root;
private TextView tvSub,tvNum,tvAdd;
private OnNumChangedListener numChangedListener;

//new 调用
public SubAddButton(Context context) {
    this(context, null);
}
// xml 使用的时候
public SubAddButton(Context context, AttributeSet attrs) {
    this(context, attrs, -1);
}
//  指定的时候
public SubAddButton(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context);
    initListener();
}

private void init(Context context){
    root = View.inflate(context,R.layout.layout_sub_add,this);

// root = LayoutInflater.from(context).inflate(R.layout.layout_sub_add,this,true);
tvSub = root.findViewById(R.id.tvSub);
tvNum = root.findViewById(R.id.tvNum);
tvAdd = root.findViewById(R.id.tvAdd);
}

private void initListener() {
    tvSub.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            sub();
        }
    });

    tvAdd.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            add();
        }
    });
}

private void add(){
    String cur = tvNum.getText().toString();
    int newNum = 0;
    if (!TextUtils.isEmpty(cur) && !cur.contains(".")){ // 非空验证
        newNum = Integer.parseInt(cur);
        newNum++;
    }
    tvNum.setText(newNum + "");
    if (numChangedListener != null){
        numChangedListener.onNumChanged(Integer.valueOf(cur),newNum);
    }
}

private void sub(){
    String cur = tvNum.getText().toString();
    int newNum = 0;

    if (!TextUtils.isEmpty(cur) && !cur.contains(".")){
        newNum = Integer.parseInt(cur);
        newNum--;
    }

    if (newNum < 0){
        newNum = 0;
        Toast.makeText(getContext(),"最小数量为0",Toast.LENGTH_SHORT).show();
        tvNum.setText(newNum + "");
    }else {
        tvNum.setText(newNum + "");
        if (numChangedListener != null){
            numChangedListener.onNumChanged(Integer.valueOf(cur),newNum);
        }
    }
}

public int getNumber(){
    String newNumber = tvNum.getText().toString();

    if (!TextUtils.isEmpty(newNumber) && !newNumber.contains(".")){
        return Integer.parseInt(newNumber);
    }
    return 0;
}

public void setNum(int newNumber){
    if (newNumber > 0){
        tvNum.setText(newNumber + "");
    }else {
        Toast.makeText(getContext(),"最小数量为0",Toast.LENGTH_SHORT).show();
    }
}

public void setNumChangedListener(OnNumChangedListener numChangedListener){
    this.numChangedListener = numChangedListener;
}

public interface OnNumChangedListener{
    void onNumChanged(int old, int number);
}

}
//Activity页面的逻辑及代码
public class MainActivity extends AppCompatActivity implements ShopCarModel.CallBackListener {

private RecyclerView recyclerView;
private ShopCarAdapter shopCarAdapter;
private ShopCarModel shopCarModel;
private CheckBox cbCheckAll;
private TextView tvTotalPrice;
private TextView tvTotalNumb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
    initListener();
    initData();
}

private void initView() {
    //在需要接受事件的类中进行注册
    EventBus.getDefault().register(this);
	
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(linearLayoutManager);
    shopCarAdapter = new ShopCarAdapter();
    recyclerView.setAdapter(shopCarAdapter);

    cbCheckAll = findViewById(R.id.cbCheckAll);
    tvTotalPrice = findViewById(R.id.tvTotalPrice);
    tvTotalNumb = findViewById(R.id.tvTotalNumb);

}

private void initListener() {
    cbCheckAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            checkAllOrNot(isChecked);
        }
    });
}

private void initData() {
    shopCarModel = new ShopCarModel();
    shopCarModel.getShopCarData(this);
}

@Override
public void success(String data) {
    ShopCarResponse response = new Gson().fromJson(data, ShopCarResponse.class);
    shopCarAdapter.setresult(response.getData());
}

private void checkAllOrNot(boolean isCheck) {
    List<MerchantResponse> listData = shopCarAdapter.getListData();
    for (int i = 0; i < listData.size(); i++) {
        MerchantResponse response = listData.get(i);
        response.setChecked(isCheck);
        List<GoodsEntity> spus = response.getSpus();

        for (int j = 0; j < spus.size(); j++) {
            GoodsEntity goodsEntity = spus.get(j);
            goodsEntity.setChecked(isCheck);
        }
    }
    shopCarAdapter.notifyDataSetChanged();
    caculatePrice();
}

private void caculatePrice(){
    List<MerchantResponse> listData = shopCarAdapter.getListData();
    int total = 0;
    int totalCount = 0;
    for (int i =0;i<listData.size();i++){
        MerchantResponse merchantResponse = listData.get(i);
        List<GoodsEntity> spus = merchantResponse.getSpus();
        for (int j=0;j<spus.size();j++){
            GoodsEntity goodsEntity = spus.get(j);
            if (goodsEntity.isChecked()){
                String price = goodsEntity.getSkus().get(0).getPrice();
                int num = goodsEntity.getPraise_num();
                total += Double.valueOf(price) * num;
                totalCount += num;
            }
        }
    }
    tvTotalNumb.setText("商品数量:"+totalCount);
    tvTotalPrice.setText("总价:"+total+"元");
}

/**
 * 响应事件的方法
 * @param event 任意自定义的java类即可
 *              注解固定写法
 *              方法名 任意
 *              方法修饰 public void
 *
 */
@Subscribe
public void onCaculateEvent(CaculateEvent event){

    int parentPosition = event.getParentPosition();
    int selfPosition = event.getSelfPosition();

    List<MerchantResponse> listData = shopCarAdapter.getListData();
    if (parentPosition != -1){
        MerchantResponse merchantResponse = listData.get(parentPosition);
        List<GoodsEntity> spus = merchantResponse.getSpus();
        if (selfPosition != -1){
            GoodsEntity goodsEntity = spus.get(selfPosition);
            goodsEntity.setPraise_num(event.getNewNum());
            if(goodsEntity.isChecked()){
                caculatePrice();
            }
        }
    }
}
@Subscribe
public void onGroupEvent(GroupEvent event){
    int groupPosition = event.getGroupPosition();
    List<MerchantResponse> listData = shopCarAdapter.getListData();
    MerchantResponse merchantResponse = listData.get(groupPosition);
    merchantResponse.setChecked(event.isChecked());
    List<GoodsEntity> spus = merchantResponse.getSpus();
    for (int i=0;i<spus.size();i++){
        GoodsEntity goodsEntity = spus.get(i);
        goodsEntity.setChecked(event.isChecked());
    }
    shopCarAdapter.notifyDataSetChanged();
    caculatePrice();
}
@Subscribe
public void onSingleEvent(SingleEvent event){
    int parentPosition = event.getParentPosition();
    int selfPosition = event.getSelfPosition();
    List<MerchantResponse> listData = shopCarAdapter.getListData();
    MerchantResponse merchantResponse = listData.get(parentPosition);
    List<GoodsEntity> spus = merchantResponse.getSpus();
    GoodsEntity goodsEntity = spus.get(selfPosition);
    goodsEntity.setChecked(event.isChecked());

    shopCarAdapter.notifyDataSetChanged();
    caculatePrice();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    //在必要的时候反注册
    EventBus.getDefault().unregister(this);
}

}
//购物车的适配器

public class ShopCarAdapter extends RecyclerView.Adapter<ShopCarAdapter.MyViewHolder> {

private List<MerchantResponse> listData = new ArrayList();

public List<MerchantResponse> getListData() {
    return listData;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View item = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_shop_car, viewGroup, false);

    return new MyViewHolder(item);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
    MerchantResponse merchantResponse = listData.get(i);
    myViewHolder.bind(merchantResponse);
}

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

public void setresult(List<MerchantResponse> listData) {
    this.listData = listData;
    notifyDataSetChanged();
}

class MyViewHolder extends RecyclerView.ViewHolder{

    private CheckedTextView tvShopName;
    private CheckBox cbShopCheck;
    private RecyclerView recyclerViewGoods;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        tvShopName = itemView.findViewById(R.id.tvShopName);
        cbShopCheck = itemView.findViewById(R.id.cbShopCheck);
        recyclerViewGoods = itemView.findViewById(R.id.recyclerViewGoods);
        cbShopCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                EventBus.getDefault().post(new GroupEvent(getAdapterPosition(),isChecked));
            }
        });
    }

    private void bind(MerchantResponse merchantResponse){
        String name = merchantResponse.getName();
        tvShopName.setText(name);
        cbShopCheck.setChecked(merchantResponse.isChecked());

        List<GoodsEntity> spus = merchantResponse.getSpus();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(itemView.getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerViewGoods.setLayoutManager(linearLayoutManager);
        int adapterPosition = getAdapterPosition();
        recyclerViewGoods.setAdapter(new GoodsAdapter(spus,adapterPosition));
    }

}

}
//购物车中商品的适配器
public class GoodsAdapter extends RecyclerView.Adapter<GoodsAdapter.MyViewHolder> {

List<GoodsEntity> listData = new ArrayList<>();
private int parentPosition = -1;

public GoodsAdapter(List<GoodsEntity> listData, int parentPosition) {
    this.listData = listData;
    this.parentPosition = parentPosition;
}

@NonNull
@Override
public GoodsAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View item = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_goods, viewGroup, false);

    return new GoodsAdapter.MyViewHolder(item);
}

@Override
public void onBindViewHolder(@NonNull GoodsAdapter.MyViewHolder myViewHolder, int i) {
    GoodsEntity goodsEntity = listData.get(i);
    myViewHolder.bind(goodsEntity);

}

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

public class MyViewHolder extends RecyclerView.ViewHolder {

    private TextView tvGoodsName,tvGoodsPrice;
    private ImageView ivGoodsPic;
    private CheckBox cbGoodsCheck;
    private SubAddButton subAddButton;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        tvGoodsName = itemView.findViewById(R.id.tvGoodsName);
        tvGoodsPrice = itemView.findViewById(R.id.tvGoodsPrice);
        ivGoodsPic = itemView.findViewById(R.id.ivGoodPic);
        cbGoodsCheck = itemView.findViewById(R.id.cbGoodsCheck);
        subAddButton = itemView.findViewById(R.id.btnSubAndAdd);

        subAddButton.setNumChangedListener(new SubAddButton.OnNumChangedListener() {
            @Override
            public void onNumChanged(int old, int number) {
                //发送事件,注册了本事件的地方会自动响应
                int selfPosition = getAdapterPosition();
                EventBus.getDefault().post(new CaculateEvent(parentPosition,selfPosition,number));
            }
        });

        cbGoodsCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                EventBus.getDefault().post(new SingleEvent(isChecked,parentPosition,getAdapterPosition()));
            }
        });
    }

    private void bind(GoodsEntity entity){
        cbGoodsCheck.setChecked(entity.isChecked());
        tvGoodsName.setText(entity.getName());
        tvGoodsPrice.setText(entity.getSkus().get(0).getPrice());
        subAddButton.setNum(entity.getPraise_num());
        Glide.with(itemView.getContext()).load(entity.getPic_url()).into(ivGoodsPic);
    }

}

}
//三个EventBus的bean类
public class CaculateEvent {

private int parentPosition = -1;
private int selfPosition = -1;
private int newNum = -1;

public CaculateEvent(int parentPosition, int selfPosition, int newNum) {
    this.parentPosition = parentPosition;
    this.selfPosition = selfPosition;
    this.newNum = newNum;
}

public int getParentPosition() {
    return parentPosition;
}

public int getSelfPosition() {
    return selfPosition;
}

public int getNewNum() {
    return newNum;
}

}

public class GroupEvent {
private int groupPosition;
private boolean isChecked;

public GroupEvent(int groupPosition, boolean isChecked) {
    this.groupPosition = groupPosition;
    this.isChecked = isChecked;
}

public int getGroupPosition() {
    return groupPosition;
}

public boolean isChecked() {
    return isChecked;
}

}

public class SingleEvent {
private boolean isChecked;
private int parentPosition;
private int selfPosition;

public SingleEvent(boolean isChecked, int parentPosition, int selfPosition) {
    this.isChecked = isChecked;
    this.parentPosition = parentPosition;
    this.selfPosition = selfPosition;
}

public boolean isChecked() {
    return isChecked;
}

public int getParentPosition() {
    return parentPosition;
}

public int getSelfPosition() {
    return selfPosition;
}

}

标签:完善,int,代码,private,购物车,listData,isChecked,void,public
来源: https://blog.csdn.net/black_amber/article/details/90311138