public class ThreeAdapter extends RecyclerView.Adapter<ThreeAdapter.MyViewHolder> {
private Context context;
private List<ShowBean.ResultBean> arr=new ArrayList<>();
//定义一个变量
private float totalPrice = 0;
public ThreeAdapter(Context context) {
this.context = context;
}
public void setData(List<ShowBean.ResultBean> list){
if(list!=null){
arr.addAll(list);
notifyDataSetChanged();
}
}
//主页面传过来的TextView
private TextView priceTotal;
public void setTextView(TextView textView){
this.priceTotal = textView;
}
//主页面传过来的CheckBox
private CheckBox mCheckBox;
public void setCheckBox(final CheckBox checkBox) {
this.mCheckBox = checkBox;
//全选 反选
mCheckBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBox checkb = (CheckBox) v;
boolean checked = checkb.isChecked();
selectAll(checked);
}
});
}
private void selectAll(boolean isChecked) {
for (int i = 0; i < arr.size(); i++) {
ShowBean.ResultBean resultsBean = arr.get(i);
resultsBean.setChecked(isChecked);
}
notifyDataSetChanged();
}
@NonNull
@Override
public ThreeAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_two, null);
MyViewHolder myViewHolder=new MyViewHolder(view);
return myViewHolder;
}
@Override
public void onBindViewHolder(@NonNull ThreeAdapter.MyViewHolder myViewHolder,final int i) {
if(arr.get(i)!=null){
myViewHolder.name.setText(arr.get(i).getCommodityName());
Glide.with(context).load(arr.get(i).getMasterPic()).into(myViewHolder.img);
myViewHolder.price.setText("¥:"+arr.get(i).getPrice());
}
//给每个checkbox设置属性
myViewHolder.select_item.setChecked(arr.get(i).isChecked());
myViewHolder.select_item.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
arr.get(i).setChecked(isChecked);
//判断 列表里面 是否都选中
boolean selectAll = isSelectAll();
//如果selectAll是true 那么传过来的checkbox(最下面那个)就选上
mCheckBox.setChecked(selectAll);
//获取价格
float price = arr.get(i).getPrice();
if (isChecked) {
//相加
totalPrice += price;
}else {
//相减
totalPrice -= price;
}
//最后 赋值
priceTotal.setText("总价:¥"+totalPrice);
}
});
}
@Override
public int getItemCount() {
return arr.size();
}
public boolean isSelectAll() {
for (int i = 0; i < arr.size(); i++) {
boolean checked = arr.get(i).isChecked();
if (!checked) {
return false;
}
}
return true;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private final TextView name;
private final ImageView img;
private final TextView price;
private final CheckBox select_item;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
img = itemView.findViewById(R.id.img);
price = itemView.findViewById(R.id.price);
select_item=itemView.findViewById(R.id.select_item);
}
}
}