Android RecyclerView realizes the shopping cart function (perfect detailed explanation - nanny level tutorial)

Shopping cart implementation image:insert image description here

First create a new model with any name, such as ShoppingCart

insert image description here

Function 1: Implementation of RecyclerView layout

①Create MainActivity
insert image description here

②Add the RecyclerView component to the MainActivity layout

◼ The layout position is as shown in the layout:
insert image description here

The recyclerview is shown in the middle part of the figure:
insert image description here

(Note: Other layouts can be realized by dragging components)

◼ The layout code of activity_main.xml is as follows:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:background="#EFE8E8"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#FF9800"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/clear"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="fill_vertical"
            android:layout_weight="1"
            android:gravity="center|start"
            android:text="   清空"
            android:textColor="#FDFAFA"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/upt"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="购物车"
            android:textColor="#F6F5F5"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/delect"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center|end"
            android:text="删除   "
            android:textColor="#F6F5F5"
            android:textSize="18sp" />
    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="640dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout1"
        app:layout_constraintVertical_bias="0.0">

    </androidx.recyclerview.widget.RecyclerView>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent">

        <CheckBox
            android:id="@+id/checkBoxall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="全选"
            android:textColor="#FF9800"
            app:layout_constraintBaseline_toBaselineOf="@+id/textView9"
            tools:layout_editor_absoluteX="1dp" />

        <TextView
            android:id="@+id/textView9"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="60dp"
            android:text="结算的价钱"
            android:textColor="#FF9800"
            app:layout_constraintStart_toEndOf="@+id/checkBoxall"
            tools:layout_editor_absoluteY="15dp" />

        <TextView
            android:id="@+id/priceall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="20dp"
            android:text="0.0"
            android:textColor="#FF9800"
            app:layout_constraintBaseline_toBaselineOf="@+id/textView9"
            app:layout_constraintStart_toEndOf="@+id/textView9" />

        <Button
            android:id="@+id/buttonall"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_marginStart="92dp"
            android:text="结算"
            app:layout_constraintBaseline_toBaselineOf="@+id/priceall"
            app:layout_constraintStart_toEndOf="@+id/priceall" />
    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

③ Create a new model class (the new model package is at the same level as shoppingcart, and a new Shop class is created in this package)

insert image description here
◼ shop class in model:
insert image description here
◼ shop class code is as follows:

package com.llw.model;

public class Shop {
    
    
    private String text1;//商品名称
    private String text2;//商品描叙
    private int price;//商品价格
    private int num;//商品数量
    private int photoId;
    private int photo_addId;
    private int photo_downId;
    private boolean isChecked;

    public Shop(String text1,String text2,int photoId,int num,int price){
    
    
        this.text1 = text1;this.text2 = text2;this.photoId = photoId;this.num = num;this.price = price;
//        ,int price,int num,int photoId,int photo_addId,int photo_downId,boolean isChecked
//        this.price = price;this.num = num;
//        this.photoId = photoId;this.photo_downId = photo_downId;this.isChecked =isChecked;
//        this.photo_addId = photo_addId;
    }
    public void setText1(String text1) {
    
    
        this.text1 = text1;
    }

    public void setText2(String text2) {
    
    
        this.text2 = text2;
    }

    public void setPrice(int price) {
    
    
        this.price = price;
    }

    public void setNum(int num) {
    
    
        this.num = num;
    }

    public void setPhotoId(int photoId) {
    
    
        this.photoId = photoId;
    }

    public void setPhoto_addId(int photo_addId) {
    
    
        this.photo_addId = photo_addId;
    }

    public void setPhoto_downId(int photo_downId) {
    
    
        this.photo_downId = photo_downId;
    }

    public void setChecked(boolean checked) {
    
    
        isChecked = checked;
    }

    public String getText1() {
    
    
        return text1;
    }

    public String getText2() {
    
    
        return text2;
    }

    public int getPrice() {
    
    
        return price;
    }

    public int getNum() {
    
    
        return num;
    }

    public int getPhotoId() {
    
    
        return photoId;
    }

    public int getPhoto_addId() {
    
    
        return photo_addId;
    }

    public int getPhoto_downId() {
    
    
        return photo_downId;
    }

    public boolean isChecked() {
    
    
        return isChecked;
    }
}

④ New Item layout

◼ The location of the item is shown in the figure:
insert image description here
◼ The layout of the item is shown in the figure:
insert image description here

◼ The code for the item layout is as follows:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:background="#FAF6F6"
    android:backgroundTint="#FFFEFE"
    android:visibility="visible"
    tools:visibility="visible">

    <CheckBox
        android:id="@+id/radio"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginStart="5dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/photo"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/photo"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="68dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/login2" />

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="11dp"
        android:layout_marginTop="7dp"
        android:text="商品名字"
        app:layout_constraintStart_toEndOf="@+id/photo"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/test2"
        android:layout_width="160dp"
        android:layout_height="30dp"
        android:layout_marginTop="4dp"
        android:text="对商品描叙"
        android:textSize="12sp"
        app:layout_constraintStart_toStartOf="@+id/text1"
        app:layout_constraintTop_toBottomOf="@+id/text1" />

    <TextView
        android:id="@+id/price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:text="100"
        android:textColor="#FF9800"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="@+id/test2" />

    <ImageView
        android:id="@+id/ptoto_down"
        android:layout_width="30dp"
        android:layout_height="15dp"
        android:layout_marginStart="3dp"
        android:layout_marginBottom="40dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/test2"
        app:layout_constraintTop_toTopOf="@+id/num"
        app:layout_constraintVertical_bias="0.0"
        app:srcCompat="@drawable/down" />

    <TextView
        android:id="@+id/num"
        android:layout_width="38dp"
        android:layout_height="16dp"
        android:layout_marginBottom="40dp"
        android:autoText="false"
        android:gravity="center"
        android:text="0"
        android:textAllCaps="false"
        android:textSize="12sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/ptoto_down" />

    <ImageView
        android:id="@+id/photo_add"
        android:layout_width="30dp"
        android:layout_height="15dp"
        app:layout_constraintBottom_toBottomOf="@+id/num"
        app:layout_constraintStart_toEndOf="@+id/num"
        app:srcCompat="@drawable/add" />

</androidx.constraintlayout.widget.ConstraintLayout>

⑤New Adapter◼
Create a new Adapter package, and create a new ShopAdapter class (adapter class) in this package:
insert image description here

◼ The adapter class should inherit the RecyclerView.Adapter class and redefine three methods:
◼ onCreateViewHolder(): used to create a ViewHolder instance (loaded custom layout)
◼ onBindViewHolder(): assign the data of the child (will be in each child Executed when the item is scrolled into the screen)
◼ getItemCount(): returns the number of sub-items of the RecyclerView
◼ A ViewHolder internal class needs to be defined in the adapter class, and these two classes are used together to define the display mode of the data

◼The code of the ShopAdapter class is as follows:

package com.llw.Adapter;

import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.llw.model.Shop;
import com.llw.shoppingcart.R;

import java.util.List;

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

    private List<Shop> list;
    public ShopAdapter(List<Shop>list){
    
    
        this.list=list;
    }
    public boolean[] flag = new boolean[100];
    public int sum=0;
    public int sum1=0;
    TextView priceAll;
    OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
    
    
        this.onItemClickListener = onItemClickListener;
    }
//接口
    public interface OnItemClickListener{
    
    
        public void OnItemClick(View view,int position);
        public void photo_addClick(@NonNull ViewHolder holder,View view,int position);
        public void photo_downClick(@NonNull ViewHolder holder,View view,int position);
    }
//计算sum和
    public int getSum1(){
    
    
        sum1=0;
        for(int i=0;i<list.size();i++){
    
    
            if(flag[i]==true){
    
    
                sum1+=list.get(i).getNum()*list.get(i).getPrice();
            }
        }
        return sum1;
    }
    public static class ViewHolder extends RecyclerView.ViewHolder{
    
    

        ImageView photo;
        ImageView photo_add;
        ImageView photo_down;
        TextView text1;
        TextView text2;
        TextView price;
        public TextView num;
        CheckBox radio;
        public ViewHolder(@NonNull View view) {
    
    
            super(view);
            photo=(ImageView) view.findViewById(R.id.photo);
            photo_add=(ImageView) view.findViewById(R.id.photo_add);
            photo_down=(ImageView) view.findViewById(R.id.ptoto_down);
            text1=(TextView) view.findViewById(R.id.text1);
            text2=(TextView) view.findViewById(R.id.test2);
            price=(TextView) view.findViewById(R.id.price);
            num=(TextView) view.findViewById(R.id.num);
            radio=(CheckBox) view.findViewById(R.id.radio);

        }
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    
    

        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.shop,parent,false);
        ViewHolder viewHolder=new ViewHolder(view);
        View view2=LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main,parent,false);
        ViewHolder viewHolder2=new ViewHolder(view2);//获取MainActivity的布局操作

        //监听事件
        //监听点击的图片事件
        viewHolder.photo.setOnClickListener(new View.OnClickListener(){
    
    

            @Override
            public void onClick(View view) {
    
    
                setPosition( viewHolder.getAdapterPosition());
                int pos=viewHolder.getAdapterPosition();
                Shop shop=list.get(pos);
                Uri webpage;
                if(shop.getPhotoId()==R.drawable.pic1){
    
    
                    webpage = Uri.parse("https://item.jd.com/100018761109.html");
                }
                else if(shop.getPhotoId()==R.drawable.pic2){
    
    
                    webpage = Uri.parse("https://item.jd.com/10023842249226.html");
                }
                else if(shop.getPhotoId()==R.drawable.pic3){
    
    
                    webpage = Uri.parse("https://item.jd.com/100018633249.html");
                }
                else if(shop.getPhotoId()==R.drawable.pic4){
    
    
                    webpage = Uri.parse("https://item.jd.com/10022335886010.html");
                }
                else if(shop.getPhotoId()==R.drawable.pic5){
    
    
                    webpage = Uri.parse("https://item.jd.com/8534207.html");
                }
                else if(shop.getPhotoId()==R.drawable.pic6){
    
    
                    webpage = Uri.parse("https://item.jd.com/100014205656.html");
                }
                else if(shop.getPhotoId()==R.drawable.pic7){
    
    
                    webpage = Uri.parse("https://item.jd.com/100027703540.html");
                }
                else if(shop.getPhotoId()==R.drawable.pic8){
    
    
                    webpage = Uri.parse("https://item.jd.com/10040851500488.html");
                }
                else if(shop.getPhotoId()==R.drawable.pic9){
    
    
                    webpage = Uri.parse("https://item.jd.com/100031564120.html");
                }
                else if(shop.getPhotoId()==R.drawable.pic10){
    
    
                    webpage = Uri.parse("https://item.jd.com/7170704.html");
                }
                else if(shop.getPhotoId()==R.drawable.pic11){
    
    
                    webpage = Uri.parse("https://item.jd.com/10036491869801.html");
                }
                else if(shop.getPhotoId()==R.drawable.pic12){
    
    
                    webpage = Uri.parse("https://item.jd.com/10032573727362.html");
                }
                else if(shop.getPhotoId()==R.drawable.pic13){
    
    
                    webpage = Uri.parse("https://item.jd.com/11820243915.html#none");
                }
                else if(shop.getPhotoId()==R.drawable.pic14){
    
    
                    webpage = Uri.parse("https://item.jd.com/1198996.html");
                }
                else {
    
    
                    webpage=Uri.parse("");
                }
                Intent intent = new Intent();
                intent.setAction( Intent.ACTION_VIEW );
                intent.setData( webpage );
                parent.getContext().startActivity(intent);
            }
        });
        //add+1
//        viewHolder.photo_add.setOnClickListener(new View.OnClickListener(){
    
    
//
//            @Override
//            public void onClick(View view) {
    
    
//                int pos=viewHolder.getAdapterPosition();
//                Shop shop= list.get(pos);
//                int x=shop.getNum();
//                x++;
//                shop.setNum(x);
//                viewHolder.num.setText(x+"");
//                if(flag[pos]==true){
    
    
//                    priceAll=view2.findViewById(R.id.priceall);
//                    priceAll.setText("一共:"+getSum1()+".0元");
//                    Toast.makeText(view.getContext(),""+priceAll.getText(),Toast.LENGTH_SHORT).show();
//
//                }
//            }
//        });

        //down-1
//        viewHolder.photo_down.setOnClickListener(new View.OnClickListener(){
    
    
//
//            @Override
//            public void onClick(View view) {
    
    
//                int pos=viewHolder.getAdapterPosition();
//                Shop shop= list.get(pos);
//                int x=shop.getNum();
//                x--;
//                if(x<0) x=0;
//                shop.setNum(x);
//                viewHolder.num.setText(x+"");
//                if(flag[pos]==true){
    
    
//                    priceAll=view2.findViewById(R.id.priceall);
//                    priceAll.setText("一共:"+getSum1()+".0元");
//                    Toast.makeText(view.getContext(),""+priceAll.getText(),Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
        //设置图片监听事件



        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    
    
        Shop shop=list.get(position);
        holder.text1.setText(shop.getText1());
        holder.text2.setText(shop.getText2());
        holder.price.setText(shop.getPrice()+".0");
        holder.num.setText(shop.getNum()+"");
        holder.photo.setImageResource(shop.getPhotoId());
 //       holder.photo_add.setImageResource(shop.getPhoto_addId());
//        holder.photo_down.setImageResource(shop.getPhoto_downId());
//        holder.radio.setVisibility(View.VISIBLE);
        //checkbutton的绑定
        holder.radio.setText((position+1)+"");//设置多选按钮的位置值,删除行后会更新
        holder.radio.setOnCheckedChangeListener(null);
        holder.radio.setChecked(flag[position]);

        holder.radio.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
    
    
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
    
    
                flag[position]=b;
            }
        });

        holder.photo_add.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                onItemClickListener.photo_addClick(holder,view,position);
            }
        });
        holder.photo_down.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                onItemClickListener.photo_downClick(holder,view,position);
            }
        });
        holder.itemView.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                onItemClickListener.OnItemClick(view,position);
            }
        });

    }

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

    private int position;
    public int getPosition() {
    
    
        return position;
    }
    public void setPosition(int position) {
    
    
        this.position = position;
    }

}

⑥Use Layout Manager

MainActivity code:

package com.llw.shoppingcart;

import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.llw.Adapter.ShopAdapter;
import com.llw.model.Shop;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    
    
    private RecyclerView recyclerView1;
    private CheckBox selectAll;
    private boolean[]f;
    private TextView clr;
    private TextView del;
    private Button buttonAll;
    private TextView priceAll;

    private List<Shop> list=new ArrayList<>();
    private RecyclerView recyclerView;
    private ShopAdapter adapter;
    public void initShop(){
    
    
            Shop shop=new Shop("5G手机 小米 红米","Redmi K50 电竞版 全新",R.drawable.pic1,1,3849);
            list.add(shop);
            Shop shop1=new Shop("全友家居餐桌椅","家用小户型吃饭桌子",R.drawable.pic2,1,4071);
            list.add(shop1);
            Shop shop2=new Shop("15.6英寸轻薄游戏本","华硕天选air 2022 12代",R.drawable.pic3,1,9999);
            list.add(shop2);
            Shop shop3=new Shop("圣闲女童爱莎公主裙","春夏款可拆披纱棉质舒适",R.drawable.pic4,1,108);
            list.add(shop3);
            Shop shop4=new Shop("高钙儿童纯牛奶","伊利 QQ星儿童纯牛奶",R.drawable.pic5,1,56);
            list.add(shop4);
            Shop shop5=new Shop("男女同款厚底熊猫鞋","老爹鞋休闲运动鞋情侣鞋",R.drawable.pic6,1,359);
            list.add(shop5);
            Shop shop6=new Shop("一次性医用外科口罩","无菌三层外科灭菌口罩",R.drawable.pic7,1,39);
            list.add(shop6);
            Shop shop7=new Shop("苹果13promax手机壳","iphone13保护套透明超薄",R.drawable.pic8,1,34);
            list.add(shop7);
            Shop shop8=new Shop("佳洁士3D炫白牙膏","美白牙膏去黄去牙渍",R.drawable.pic9,1,27);
            list.add(shop8);
            Shop shop9=new Shop("大连美早樱桃","车厘子巨无霸JJJ级",R.drawable.pic10,1,160);
            list.add(shop9);
            Shop shop10=new Shop("华为nova9","9号色 8+128G全网通",R.drawable.pic11,1,2519);
            list.add(shop10);
            Shop shop11=new Shop("蓝牙耳机","oppo 白色尊享升级版",R.drawable.pic12,1,89);
            list.add(shop11);
            Shop shop12=new Shop(" T9民谣吉他","新手入门练习琴guitar",R.drawable.pic13,1,175);
            list.add(shop12);
            Shop shop13=new Shop("卡西欧(CASIO)手表","商务休闲男表石英表",R.drawable.pic14,1,505);
            list.add(shop13);

    }

    public void initRecyclerView2() {
    
    
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        // 定义一个线性布局管理器(默认是垂直排列)
        LinearLayoutManager layoutManager = new LinearLayoutManager(this); //默认垂直排列
        recyclerView.setLayoutManager(layoutManager);
        adapter = new ShopAdapter(list);
        recyclerView.setAdapter(adapter);

        //添加默认的分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
    }


    //全选和全不选功能
    public void selectAll(){
    
    
        selectAll=(CheckBox)findViewById(R.id.checkBoxall);
        recyclerView=(RecyclerView) findViewById(R.id.recyclerView);
        f=new boolean[100];
        selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    
    
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
    
    
                if(b==true){
    
    
                    for(int i=0;i<100;i++){
    
    
                        adapter.flag[i]=true;
                        adapter.notifyDataSetChanged();
                    }
                }
                else{
    
    
                    for(int i=0;i<100;i++){
    
    
                        adapter.flag[i]=false;
                        adapter.notifyDataSetChanged();
                    }
                }
                //更新数据
                // adapter = new ShopAdapter(list);
                // adapter.notifyDataSetChanged();
            }
        });
    }
    //移除功能
    public void removeItem(int position){
    
    
        list.remove(position);
        adapter.notifyItemRemoved(position);
        adapter.notifyItemRangeChanged(position,list.size());//必须用这个不然会紊乱
    }
    //删除功能
    public  void delete(){
    
    
        del=(TextView)findViewById(R.id.delect);
        del.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
              //  Toast.makeText(MainActivity.this,"删除功能",Toast.LENGTH_SHORT).show();
                for(int i=0;i<list.size();i++){
    
    
                    if(adapter.flag[i]==true){
    
    
                        removeItem(i);
                        //删除list数组后还要更新flag数组 i没有了i+1的变成了i所有flag[i]=flag[1+1]
                        for(int j=i;j<list.size()-1;j++) adapter.flag[j]=adapter.flag[j+1];
                        //删除后i,i--才行,列如第0行删除后仍然从第0行开始
                        i--;
                    }
                }
            }
        });
    }
    //清空功能
    public void clear(){
    
    
        clr=(TextView)findViewById(R.id.clear);
        clr.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
            //    Toast.makeText(MainActivity.this,"清空功能",Toast.LENGTH_SHORT).show();
                list.clear();
                adapter.notifyDataSetChanged();
            }
        });
    }
    //计算合计总价钱
    public void allPrice(){
    
    
        buttonAll=(Button)findViewById(R.id.buttonall);
        priceAll=(TextView)findViewById(R.id.priceall);
        buttonAll.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                priceAll.setText(adapter.getSum1()+".0");
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initShop();
        initRecyclerView2();
        selectAll();
        delete();
        clear();
        allPrice();

        //ActionBar
        ActionBar actionBar=getSupportActionBar();
        actionBar.hide();
        //清屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setEventListener();
    }

    private void setEventListener() {
    
    
        adapter.setOnItemClickListener(new ShopAdapter.OnItemClickListener() {
    
    
            @Override
            public void OnItemClick(View view, int position) {
    
    
                priceAll.setText(adapter.getSum1()+".0元");
            }

            @Override
            public void photo_addClick(ShopAdapter.ViewHolder holder, View view, int position) {
    
    
                Shop shop= list.get(position);
                int x=shop.getNum();
                x++;
                shop.setNum(x);
                holder.num.setText(x+"");
                if(adapter.flag[position]==true){
    
    
                    priceAll.setText(adapter.getSum1()+".0元");
                }
            }

            @Override
            public void photo_downClick(ShopAdapter.ViewHolder holder, View view, int position) {
    
    
                Shop shop= list.get(position);
                int x=shop.getNum();
                x--;
                if(x<0) x=0;
                shop.setNum(x);
                holder.num.setText(x+"");
                if(adapter.flag[position]==true){
    
    
                    priceAll.setText(adapter.getSum1()+".0元");
                }
            }
        });
    }

}

<< After the code is pasted, let’s explain the function below! >>
The main function of adding layout function is:

initShop()
initRecyclerView2()

All other functions are originally written in the ShopAdapter, but in order to update the total price of the main layout in real time when the item plus or minus button is clicked, the interface is used to write the item's monitoring event to MainActivity to monitor the modified code as above: add the function
below Subtract, select all, clear, and delete codes are explained step by step:

Function 2: Addition, subtraction and settlement

First, the implementation steps of the interface are as follows:

The interface implementation code in ShopAdapter:
①Add it outside all the functions in the class

  OnItemClickListener onItemClickListener;
      public interface OnItemClickListener{
    
    
        public void OnItemClick(View view,int position);
        public void photo_addClick(@NonNull ViewHolder holder,View view,int position);
        public void photo_downClick(@NonNull ViewHolder holder,View view,int position);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
    
    
        this.onItemClickListener = onItemClickListener;
    }
    


Add in the function onBindViewHolder

        holder.photo_add.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                onItemClickListener.photo_addClick(holder,view,position);
            }
        });
        holder.photo_down.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                onItemClickListener.photo_downClick(holder,view,position);
            }
        });
        holder.itemView.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                onItemClickListener.OnItemClick(view,position);
            }
        });

Three steps to call the interface function in MainActivity

MainActivity中

private void setEventListener() {
    
    
        adapter.setOnItemClickListener(new ShopAdapter.OnItemClickListener() {
    
    
            @Override
            public void OnItemClick(View view, int position) {
    
    
                priceAll.setText(adapter.getSum1()+".0元");
            }

            @Override
            public void photo_addClick(ShopAdapter.ViewHolder holder, View view, int position) {
    
    
                Shop shop= list.get(position);
                int x=shop.getNum();
                x++;
                shop.setNum(x);
                holder.num.setText(x+"");
                if(adapter.flag[position]==true){
    
    
                    priceAll.setText(adapter.getSum1()+".0元");
                }
            }

            @Override
            public void photo_downClick(ShopAdapter.ViewHolder holder, View view, int position) {
    
    
                Shop shop= list.get(position);
                int x=shop.getNum();
                x--;
                if(x<0) x=0;
                shop.setNum(x);
                holder.num.setText(x+"");
                if(adapter.flag[position]==true){
    
    
                    priceAll.setText(adapter.getSum1()+".0元");
                }
            }
        });
    }

It can realize the addition and subtraction function and update the settlement price at the same time

Function three select all, clear, delete

The realization of function three is mainly to define an array in ShopAdapter

public boolean[] flag = new boolean[100];

And in onBindViewHolder use

holder.radio.setText((position+1)+"");//设置多选按钮的位置值,删除行后会更新
holder.radio.setChecked(flag[position]);//设置多选按钮状态

In MainActivity:
① Select all and none

 public void selectAll(){
    
    
        selectAll=(CheckBox)findViewById(R.id.checkBoxall);
        recyclerView=(RecyclerView) findViewById(R.id.recyclerView);
        f=new boolean[100];
        selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    
    
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
    
    
                if(b==true){
    
    
                    for(int i=0;i<100;i++){
    
    
                        adapter.flag[i]=true;
                        adapter.notifyDataSetChanged();
                    }
                }
                else{
    
    
                    for(int i=0;i<100;i++){
    
    
                        adapter.flag[i]=false;
                        adapter.notifyDataSetChanged();
                    }
                }
                //更新数据
                // adapter = new ShopAdapter(list);
                // adapter.notifyDataSetChanged();
            }
        });
    }

②Empty

    public void clear(){
    
    
        clr=(TextView)findViewById(R.id.clear);
        clr.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
            //    Toast.makeText(MainActivity.this,"清空功能",Toast.LENGTH_SHORT).show();
                list.clear();
                adapter.notifyDataSetChanged();
            }
        });
    }

③Delete function

    public  void delete(){
    
    
        del=(TextView)findViewById(R.id.delect);
        del.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
              //  Toast.makeText(MainActivity.this,"删除功能",Toast.LENGTH_SHORT).show();
                for(int i=0;i<list.size();i++){
    
    
                    if(adapter.flag[i]==true){
    
    
                        removeItem(i);
                        //删除list数组后还要更新flag数组 i没有了i+1的变成了i所有flag[i]=flag[1+1]
                        for(int j=i;j<list.size()-1;j++) adapter.flag[j]=adapter.flag[j+1];
                        //删除后i,i--才行,列如第0行删除后仍然从第0行开始
                        i--;
                    }
                }
            }
        });
    }

Settlement during function:
ShopAdapter writes the function of calculating the total price:

 public int getSum1(){
    
    
        sum1=0;
        for(int i=0;i<list.size();i++){
    
    
            if(flag[i]==true){
    
    
                sum1+=list.get(i).getNum()*list.get(i).getPrice();
            }
        }
        return sum1;
    }

MainActivity中:

//计算合计总价钱
    public void allPrice(){
    
    
        buttonAll=(Button)findViewById(R.id.buttonall);
        priceAll=(TextView)findViewById(R.id.priceall);
        buttonAll.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                priceAll.setText(adapter.getSum1()+".0");
            }
        });
    }

The writing process of all functions has been completed:
the last drawable image sharing link:

Link: https://pan.baidu.com/s/1lsSRDkpU00XK9FqBirdpPg
Extraction code: o75e

Guess you like

Origin blog.csdn.net/qq_54537215/article/details/125699818