Saturday, March 14, 2020

RecyclerView in Android Tutorial

Use RecylerView to display data as a horizontal list LinearLayoutManager, grid with GridLayoutManager, StaggeredGridLayoutManager, effects when scrolling elements, capturing events and aligning with SnapHelper, building detailed Adapters

Overview of RecyclerView in Android

RecyclerView it used to build UI similar to the operation of ListView, GridView. It represents the list with different presentation styles, vertically and horizontally. It is a much better ListView support library out used in CoordinatorLayout to interact with other UI components.
RecyclerView is also very suitable when display data collected during the application run, such as based on user interaction, on downloaded data
RecyclerView in Android Tutorial

Integration into library build.gradle as follows to use RecyclerView
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:recyclerview-v7:26.1.0'
implementation 'com.android.support:design:26.1.0'
When using RecylerView, you also need to work with:
RecyclerView.Adapter Manage data and update the data to display in the View (display elements in the RecyclerView)
RecyclerView.Layout Manager
RecyclerView.ItemAnimator Class to build animation (dynamic) for events on the display element, such as the effect when adding an element, removing an element from RecyclerView
RecyclerView.Viewholder class used to assign / update data into elements.

Example RecyclerView in Android studio

First, you need to build a student data representation model (Mode), you can build that class as follows:
public class Student {
    private String mName;
    private int birthYear;
    public void setmName(String mName) {
        this.mName = mName;
    }
    public void setBirthYear(int birthYear) {
        this.birthYear = birthYear;
    }
    public Student(String mName, int birthYear) {
        this.mName = mName;
        this.birthYear = birthYear;
    }
    public String getmName() {
        return mName;
    }
    public int getBirthYear() {
        return birthYear;
    }
}
RecyclerView in Layout
Next in Layout XML (for example activity_recycler_view_example_active.xml) add RecyclerView the following form:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    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:fitsSystemWindows="false"
    <android.support.v7.widget.RecyclerView
        android:id="@+id/studentsList"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>
</android.support.design.widget.CoordinatorLayout>
For example, create a layout named student_item.xml and update the following content:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    >
    <ImageView
        android:layout_width="60dp"
        android:layout_height="match_parent"
        android:src="@android:drawable/ic_menu_gallery" />
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="0dp"
        android:paddingLeft="5dp"
        android:layout_weight="1"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/studentname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:textSize="16sp"
            android:text="dsafdsfdsfasf"

            />
        <TextView
            android:id="@+id/birthyear"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textStyle="italic"
            android:textSize="14sp"
            android:text="dsfadsfdsf"
            />
    </LinearLayout>
    <Button
        android:id="@+id/detail_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:textSize="10sp"
        android:text="Chi tiết"
        />
</LinearLayout>
Write Adapter and ViewHolder
Create an Adapter that inherits from RecyclerView.Adapter, for example, named StudentAdapter, its function is to make RecycleView interact with the data to display. Specifically we will overload the methods in the Adapter

  • getItemCount (): indicates the number of elements of the data
  • onCreateViewHolder: create a ViewHolder object, in which it contains the View to display data
  • onBindViewHolder: transfers element data to ViewHolder
The StudentAdapter also uses a class named ViewHolder that inherits RecyclerView.ViewHolder, which holds the View display of data.
StudentAdapter and ViewHolder present the following code:
public class StudentAdapter extends RecyclerView.Adapter {
        private List mStutents;
        private Context mContext;
        public StudentAdapter(List _student, Context mContext) {
            this.mStutents = _student;
            this.mContext = mContext;
        }
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            Context context = parent.getContext();
            LayoutInflater inflater = LayoutInflater.from(context);
         
            View studentView =
                    inflater.inflate(R.layout.student_item, parent, false);
            ViewHolder viewHolder = new ViewHolder(studentView);
            return viewHolder;
        }
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Student student = mStutents.get(position);
            holder.studentname.setText(student.getmName());
            holder.birthyear.setText(student.getBirthYear()+"");

        }
        @Override
        public int getItemCount() {
            return mStutents.size();
        }
            public class ViewHolder extends RecyclerView.ViewHolder {
            private View itemview;
            public TextView studentname;
            public TextView birthyear;
            public Button detail_button;
            public ViewHolder(View itemView) {
                super(itemView);
                itemview = itemView;
                studentname = itemView.findViewById(R.id.studentname);
                birthyear = itemView.findViewById(R.id.birthyear);
                detail_button = itemView.findViewById(R.id.detail_button);
                detail_button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(view.getContext(),
                                       studentname.getText() +" | "
                                       + " Demo function", Toast.LENGTH_SHORT)
                                       .show();
                    }
                });
            }
        }

    }
RecyclerView setup code - Set LayoutManager and Adapter
Now it's time to use the above results, in Activity's onCreate you can add the following code:
RecyclerView recyclerView;
StudentAdapter adapter;
ArrayList<Student> students;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recycler_view_example_active);
    recyclerView = findViewById(R.id.studentsList);
    students = new ArrayList<Student>();
    //Tự phát sinh 50 dữ liệu mẫu
    for (int i = 1; i <= 50; i++) {
        students.add(new Student("Student Name"+i , 1995 + (i % 2)));
    }
    adapter = new StudentAdapter(students, this);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    recyclerView.setAdapter(adapter);
    recyclerView.setLayoutManager(linearLayoutManager);
}

1 comment:


  1. I really enjoyed reading this post, I always appreciate topics like this being discussed to us. Information very nice. I will follow post Thanks for sharing. COVID-19 | Download gta 5 game apk for android phone

    ReplyDelete