Android learning records (13)

1. Circulator view

1.1 Overview of the circulator view

RecyclerView is a new control introduced by Android in the support-v7 library. The Chinese alias is the recycler view. Its function is very powerful. It can realize the display effects of ListView, GridView, and waterfall grid respectively.

1.2 Common methods of looper view

setAdapter: Set the adapter of the list item. See the next heading for a detailed description of the adapter.
setLayoutManager: Set the layout manager of the list item. There are currently three types: linear layout manager LinearLayoutManager, grid layout manager GridLayoutManager, waterfall grid layout manager StaggeredGridLayoutManager. For a detailed description of the layout manager, see the second half of this article.
addItemDecoration: Add the dividing line of the list item.
removeItemDecoration: Remove the dividing line of the list item.
setItemAnimator: Set the addition and deletion animation of list items.
addOnItemTouchListener: Add a touch listener for list items. Because RecyclerView does not implement the click interface of list items, developers can monitor user gestures through the touch listener here.
removeOnItemTouchListener: Remove the touch listener for the list item.

1.3 Loop adapter

RecyclerView has a special adapter class, namely RecyclerView.Adapter. Before calling the setAdapter method of RecyclerView, we must first implement a data adapter derived from RecyclerView.Adapter to define the layout and specific operations of the list items. The following are common methods related to RecyclerView.Adapter:

Here are the methods that must be overridden for custom adapters:

getItemCount: Get the number of list items.
onCreateViewHolder: Create the view holder of the entire layout. The input parameters include the view type, and different layouts can be loaded according to the view type, so as to realize the headed list layout.
onBindViewHolder: Bind each item's view holder.
The following methods can be overridden or not:
getItemViewType: Returns the view type of each item. The view type returned here is used by the onCreateViewHolder method.
getItemId: Get the number of each item.
The following methods can be called directly:
notifyItemInserted: notify the adapter that a new item is inserted at the specified position.
notifyItemRemoved: Notify the adapter that the original item is deleted at the specified location. notifyItemChanged: Notify the adapter that the item at the specified position has changed. notifyDataSetChanged: Notify the adapter that the data in the entire list has changed.

In general, RecyclerView.Adapter and the BaseAdapter we often encountered before are basically the same in processing flow. Of course, there are also many differences between them. The following are the main differences between RecyclerView.Adapter and other adapters:

1. Built-in ViewHolder and its reuse function, no need for developers to manually reuse ViewHolder;
2. Click and long-press functions for list items that are not built-in, require developers to monitor click and long-press events themselves;
3. Add to distinguish different lists The item’s view type makes it convenient for developers to load different layouts according to the type;
4. Individual items can be added, deleted, or modified individually without refreshing the entire list;

2. Case demonstration

2.1 New Android project

Insert picture description here
Insert picture description here

2.2 Add dependency on recyclerview library to Android application

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

2.3 Add picture background

Insert picture description here
Insert picture description here

2.4 activity_main.xml

Insert picture description here

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:padding="15dp"
    tools:context=".MainActivity">

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

2.5 student_list_item.xml

Insert picture description here

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/ivStudentIcon"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:src="@drawable/img1" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:gravity="center_vertical"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tvStudentName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:textColor="#0000ff"
            android:textSize="25sp" />

        <TextView
            android:id="@+id/tvStudentPhone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:textColor="#555555"
            android:textSize="20sp" />
    </LinearLayout>
</LinearLayout>

2.6 Create student entity class

Insert picture description here
Insert picture description here

package net.nell.studentlist;


public class Student {
    
    
    private int studentIcon;
    private String studentName;
    private String studentPhone;

    public int getStudentIcon() {
    
    
        return studentIcon;
    }

    public void setStudentIcon(int studentIcon) {
    
    
        this.studentIcon = studentIcon;
    }

    public String getStudentName() {
    
    
        return studentName;
    }

    public void setStudentName(String studentName) {
    
    
        this.studentName = studentName;
    }

    public String getStudentPhone() {
    
    
        return studentPhone;
    }

    public void setStudentPhone(String studentPhone) {
    
    
        this.studentPhone = studentPhone;
    }

    @Override
    public String toString() {
    
    
        return "Student{" +
                "studentIcon=" + studentIcon +
                ", studentName='" + studentName + '\'' +
                ", studentPhone='" + studentPhone + '\'' +
                '}';
    }
}

2.7 Main interface class

Insert picture description here

package net.nell.studentlist;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;

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

public class MainActivity extends AppCompatActivity {
    
    

    private RecyclerView rvStudent; // 学生循环器视图(展示)
    private RecyclerView.Adapter adapter; // 循环器适配器(桥梁)
    private List<Student> students; // 学生列表(数据源)

    @SuppressLint("WrongConstant")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        // 利用布局资源文件设置用户界面
        setContentView(R.layout.activity_main);

        // 通过资源标识符获取控件实例
        rvStudent = findViewById(R.id.rvStudent);

        // 获取学生列表作为数据源
        students = getStudents();

        // 创建线性布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        // 设置线性布局管理器方向属性(默认是VERTICAL)
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        // 给循环器视图设置布局管理器
        rvStudent.setLayoutManager(layoutManager);

        // 初始化循环器适配器
        adapter = new RecyclerView.Adapter() {
    
    
            /**
             * 视图容器
             */
            class ViewHolder extends RecyclerView.ViewHolder {
    
    
                private ImageView ivStudentIcon;
                private TextView tvStudentName;
                private TextView tvStudentPhone;

                public ViewHolder(@NonNull View itemView, ImageView ivStudentIcon, TextView tvStudentName, TextView tvStudentPhone) {
    
    
                    super(itemView);
                    this.ivStudentIcon = ivStudentIcon;
                    this.tvStudentName = tvStudentName;
                    this.tvStudentPhone = tvStudentPhone;
                }

                public ImageView getIvStudentIcon() {
    
    
                    return ivStudentIcon;
                }

                public TextView getTvStudentName() {
    
    
                    return tvStudentName;
                }

                public TextView getTvStudentPhone() {
    
    
                    return tvStudentPhone;
                }
            }

            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    
    
                // 获取视图对象(将列表项模板转换成视图)
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.student_list_item, parent, false);
                // 获取视图里的控件
                ImageView ivStudentIcon = view.findViewById(R.id.ivStudentIcon);
                TextView tvStudentName = view.findViewById(R.id.tvStudentName);
                TextView tvStudentPhone = view.findViewById(R.id.tvStudentPhone);

                // 创建视图容器
                RecyclerView.ViewHolder viewHolder = new ViewHolder(view, ivStudentIcon, tvStudentName, tvStudentPhone);

                // 返回视图容器
                return viewHolder;
            }

            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
    
    
                // 获取学生数据
                Student student = students.get(position);

                // 获取控件实例
                ImageView ivStudentIcon = ((ViewHolder)holder).getIvStudentIcon();
                TextView tvStudentName = ((ViewHolder)holder).getTvStudentName();
                TextView tvStudentPhone = ((ViewHolder)holder).getTvStudentPhone();

                // 设置控件属性
                ivStudentIcon.setImageResource(student.getStudentIcon());
                tvStudentName.setText(student.getStudentName());
                tvStudentPhone.setText(student.getStudentPhone());

                // 给控件设置监听器
                ivStudentIcon.setOnClickListener(new View.OnClickListener() {
    
    
                    @Override
                    public void onClick(View v) {
    
    
                        Toast.makeText(MainActivity.this, student.getStudentName()
                                + " : " + student.getStudentPhone(), Toast.LENGTH_SHORT).show();
                    }
                });
                tvStudentName.setOnClickListener(new View.OnClickListener() {
    
    
                    @Override
                    public void onClick(View v) {
    
    
                        Toast.makeText(MainActivity.this, student.getStudentName()
                                + " : " + student.getStudentPhone(), Toast.LENGTH_SHORT).show();
                    }
                });
                tvStudentPhone.setOnClickListener(new View.OnClickListener() {
    
    
                    @Override
                    public void onClick(View v) {
    
    
                        Toast.makeText(MainActivity.this, student.getStudentName()
                                + " : " + student.getStudentPhone(), Toast.LENGTH_SHORT).show();
                    }
                });
            }

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

        // 给循环器视图设置适配器
        rvStudent.setAdapter(adapter);

        // 给循环器视图添加列表项分隔线
        rvStudent.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
    }

    /**
     * @return 学生列表
     */
    private List<Student> getStudents() {
    
    
        // 创建学生列表
        List<Student> students = new ArrayList<>();
        // 声明学生
        Student student = null;

        // 创建第1个学生
        student = new Student();
        student.setStudentIcon(R.drawable.img1);
        student.setStudentName("李晓红");
        student.setStudentPhone("15878782345");
        // 将学生添加到学生列表
        students.add(student);

        // 创建第2个学生
        student = new Student();
        student.setStudentIcon(R.drawable.img2);
        student.setStudentName("王晓玲");
        student.setStudentPhone("15956567890");
        // 将学生添加到学生列表
        students.add(student);

        // 创建第3个学生
        student = new Student();
        student.setStudentIcon(R.drawable.img3);
        student.setStudentName("董大伟");
        student.setStudentPhone("13567891230");
        // 将学生添加到学生列表
        students.add(student);

        // 创建第4个学生
        student = new Student();
        student.setStudentIcon(R.drawable.img4);
        student.setStudentName("尚洪文");
        student.setStudentPhone("18856789032");
        // 将学生添加到学生列表
        students.add(student);

        // 创建第5个学生
        student = new Student();
        student.setStudentIcon(R.drawable.img5);
        student.setStudentName("唐语涵");
        student.setStudentPhone("15967893450");
        // 将学生添加到学生列表
        students.add(student);

        // 创建第6个学生
        student = new Student();
        student.setStudentIcon(R.drawable.img6);
        student.setStudentName("郑智化");
        student.setStudentPhone("15867678904");
        // 将学生添加到学生列表
        students.add(student);

        // 创建第7个学生
        student = new Student();
        student.setStudentIcon(R.drawable.img7);
        student.setStudentName("童安格");
        student.setStudentPhone("13845674560");
        // 将学生添加到学生列表
        students.add(student);

        // 返回学生列表
        return students;
    }
}

2.8 Operation effect

Insert picture description here
Insert picture description here
I haven't completed the task in the past few days, and learned a little new thing, but also because I want to have more ideas in the process of completing the next task. In the process of making pages, you can also know how to layout more efficiently. Tomorrow, I will complete the new task, and the knowledge involved will be reflected in my blog tomorrow.

Guess you like

Origin blog.csdn.net/weixin_46705517/article/details/112969296