[Android learning notes] basic usage of RecyclerView 1

1, Brief introduction

1 what is RecyclerView?

A flexible view for providing a limited window into a large data set.

RecyclerView is a scrolling list of elements displayed according to the dataset.

2 what are the characteristics of recyclerview?

a. Optimized ListView
b. ViewHolder ---- encapsulate the view
c. The layoutmanager layout manager controls how items are laid out
d. ItemDecoration sets the interval style of an Item
e. Item animato controls the animation of adding and deleting items

Here d and e are not available for the time being. You can understand them yourself.
Usage of ItemDecoration
Usage of ItemAnimato

ListView: the layout is relatively single, with only one vertical effect. (as shown in the figure)

RecyclerView: rich layout effects. You can set linear layout (vertical and horizontal), table layout and waterfall flow layout in LayoutMananger.

II. Basic usage examples

1. Achieve the same effect as ListView (vertical)

Achieve the same effect as ListView, and place pictures vertically:

Steps:
(1) Add dependent Library:
Open the app/build.gradle file and add the following contents to the dependencies closure:

implementation "androidx.recyclerview:recyclerview:1.1.0"

The first line of code uses the following dependency package, but I will report an error here. You can check your version and modify it according to the specific situation.

implementation 'com.android.support:recyclerview-v7:24.2.1'

to glance at:

Remember to click sync now.

(2) In activity_ Add the RecyclerView control to the main.xml layout file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

(3) New Fruit class

public class Fruit {
    private String name;
    private int imageId;

    public Fruit(String name, int imageId){
        this.name = name;
        this.imageId = imageId;
    }

    public String getName(){
        return name;
    }

    public int getImageId(){
        return imageId;
    }
}

(4) New fruit_item.xml file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/fruit_image"
        android:layout_width="100dp"
        android:layout_height="100dp"/>

    <TextView
        android:id="@+id/fruit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"/>
</LinearLayout>

(5) Modify the code in MainActivity.java (don't forget to add the picture file to drawable)

public class MainActivity extends AppCompatActivity {

    private List<Fruit> fruitList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
		initFruit();//Initialize fruit data
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        FruitAdapter adapter = new FruitAdapter(fruitList);
        recyclerView.setAdapter(adapter);
    }

    private void initFruit(){
        for(int i=0 ; i<2 ; i++){
            Fruit apple = new Fruit("Apple",R.drawable.apple_pic);
            fruitList.add(apple);
            Fruit banana = new Fruit("Banana",R.drawable.banana_pic);
            fruitList.add(banana);
            Fruit orange = new Fruit("Orange",R.drawable.orange_pic);
            fruitList.add(orange);
            Fruit grape = new Fruit("Grape",R.drawable.grape_pic);
            fruitList.add(grape);
            Fruit pineapple = new Fruit("Pineapple",R.drawable.pineapple_pic);
            fruitList.add(pineapple);
        }
    }
}

That's it. Run the virtual machine and see the effect!!

2. Realize horizontal rolling layout

Steps:
(1) Yes, fruit_ Modify the code of item.xml: add orientation, modify the width of the layout, adjust each control to the horizontal center, and then use marginTop to keep some distance between text and pictures.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="120dp"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/fruit_image"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center_horizontal"/>

    <TextView
        android:id="@+id/fruit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"
        android:gravity="center_horizontal"
        android:layout_marginTop="10dp"/>
</LinearLayout>

(2) Modify the code in MainActivity.java, add a line of code in onCreate method, and set the direction.

layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

Run the virtual machine again and slide the page left and right to see the effect.

3. Realize waterfall flow layout

(1) Yes, fruit_ Modify the code of item.xml: because the width of waterfall flow layout is automatically adapted according to the number of columns in the layout, not a fixed value, change the width to match_parent. layout_ The margin property leaves space between children. TextView is left aligned. If the length of the text becomes longer, it will not be strange to display it.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    >

    <ImageView
        android:id="@+id/fruit_image"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center_horizontal"/>

    <TextView
        android:id="@+id/fruit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:layout_marginLeft="10dp"
        android:gravity="center_horizontal"
        android:layout_marginTop="10dp"/>
</LinearLayout>

(2) Modify the code in MainActivity.java:

  • Delete the original linear layout in the onCreate method, and then create an instance of StaggerGridLayoutManager. Its constructor receives two parameters, one is to specify the number of columns of the layout (three columns are passed in here), and the other is to specify the arrangement direction of the layout.
  • In order to make the effect of waterfall flow more obvious, we adjust the height of each sub item to make them inconsistent. We add the getRandomLengthName() method to create a random number to control the height.
 public class MainActivity extends AppCompatActivity {

    private List<Fruit> fruitList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFruit();//Initialize fruit data
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        FruitAdapter adapter = new FruitAdapter(fruitList);
        recyclerView.setAdapter(adapter);
    }

    private void initFruit() {
        for (int i = 0; i < 2; i++) {
            Fruit apple = new Fruit(getRandomLengthName("Apple"), R.drawable.apple_pic);
            fruitList.add(apple);
            Fruit banana = new Fruit(getRandomLengthName("Banana"), R.drawable.banana_pic);
            fruitList.add(banana);
            Fruit orange = new Fruit(getRandomLengthName("Orange"), R.drawable.orange_pic);
            fruitList.add(orange);
            Fruit grape = new Fruit(getRandomLengthName("Grape"), R.drawable.grape_pic);
            fruitList.add(grape);
            Fruit pineapple = new Fruit(getRandomLengthName("Pineapple"), R.drawable.pineapple_pic);
            fruitList.add(pineapple);
        }
    }
    private String getRandomLengthName(String name){
        Random random = new Random();
        int length = random.nextInt(20)+1;
        StringBuilder builder = new StringBuilder();
        for(int i=0;i<length;i++){
            builder.append(name);
        }
        return builder.toString();
    }
}

4. Add click event to RecyclerView

(1) Modify the code in the FruitAdapter: define the View fruitView, add the fruitView variable in the ViewHolder to maintain the instance of the outermost layout of the child item, and then register the click event in the onCreateViewHolder() method. In the two click events, first obtain the position clicked by the user, then obtain the Fruit instance through the position, and then use the Toast prompt.

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

    private List<Fruit> mFruitList;

    //Create an instance of ViewHolder and set fruit_ The layout of item.xml is loaded in and passed into the constructor
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item,parent,false);
        final ViewHolder holder = new ViewHolder(view);
        holder.fruitView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                int position = holder.getAdapterPosition();
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(v.getContext(),"you clicked view"+fruit.getName(),Toast.LENGTH_SHORT).show();;
            }
        });
        holder.fruitImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = holder.getAdapterPosition();
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(view.getContext(),"you clicked image "+fruit.getName(),Toast.LENGTH_SHORT).show();
            }
        });
        return holder;
    }

    //Assigning values to the children of RecyclerView will be executed when the children are scrolled to the screen
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Fruit fruit = mFruitList.get(position);
        holder.fruitImage.setImageResource(fruit.getImageId());
        holder.fruitName.setText(fruit.getName());
    }

    //Returns the number of children of RecyclerView
    @Override
    public int getItemCount() {
        return mFruitList.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder{
        ImageView fruitImage;
        TextView fruitName;
        View fruitView;

        public ViewHolder(View view) {
            super(view);
            fruitView = view;
            fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
            fruitName = (TextView) view.findViewById(R.id.fruit_name);
        }
    }
    //This is a constructor that assigns the passed data source to mFruitList
    public FruitAdapter(List<Fruit> fruitList){
        mFruitList = fruitList;
    }

}

Run and see the effect!

Here is the basic usage of RecyclerView. 😜

Tags: Java Android

Posted on Sun, 21 Nov 2021 17:17:27 -0500 by rathersurf