public class ShoppingRecyclerAdapter extends RecyclerView.Adapter<ShoppingRecyclerAdapter.ViewHolder> {
private Context context;
List list =new ArrayList<>();
public ShoppingRecyclerAdapter(Context context) {
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.shopping_backgroun_item, null, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int i) {
final ShoppingChildBean good=list.get(i);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.ic_launcher_background)
.error(R.drawable.ic_launcher_foreground);
Glide.with(context).load(good.pic).apply(requestOptions).into(holder.image);
holder.shoppingtext.setText(good.commodityName);
holder.shoppingtextnum.setText(good.count+"");
holder.shoppingrecyclerprice.setText("$"+good.price+"");
holder.checkbox.setChecked(good.check);
holder.checkbox.setTag(good);
//选中
holder.checkbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
good.check=((CheckBox)v).isChecked();
//计算价格
notifyDataSetChanged();
isCheck();
}
});
//添加
holder.add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
good.count++;
good.setCount(good.count);
//计算价格
notifyDataSetChanged();
}
});
//减少
holder.sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (good.count>1){
good.count--;
}else {
}
//计算价格
good.setCount(good.count);
notifyDataSetChanged();
}
});
}
public void isCheck() {
int a=0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).check){
a++;
}
}
shoppingData.getData(a);
}
//定义接口回调
public interface ShoppingData{
void getData(int a);
}
public ShoppingData shoppingData;
public void setShoppingData(ShoppingData shoppingData) {
this.shoppingData = shoppingData;
}
@Override
public int getItemCount() {
return list.size();
}
public void clear() {
list.clear();
}
public void add(List<ShoppingChildBean> shoppingCartList) {
if (shoppingCartList != null) {
list.addAll(shoppingCartList);
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
CheckBox checkbox;
ImageView image;
TextView shoppingtext,shoppingrecyclerprice,shoppingtextnum;
Button add,sub;
public ViewHolder(@NonNull View itemView) {
super(itemView);
checkbox=itemView.findViewById(R.id.checkbox);
image=itemView.findViewById(R.id.image);
shoppingtext=itemView.findViewById(R.id.shoppingtext);
shoppingrecyclerprice=itemView.findViewById(R.id.shoppingrecyclerprice);
shoppingtextnum=itemView.findViewById(R.id.shoppingtextnum);
add=itemView.findViewById(R.id.add);
sub=itemView.findViewById(R.id.sub);
}
}
}