Hướng dẫn thực hành sử dụng RecyclerView hiển thị dữ liệu trong android java

03cd82 2024

1. Tạo lớp đối tượng dữ liệu

public class SanPham {

    public int id;
    public String name;

    public SanPham(int id, String name){

        this.id = id;
        this.name = name;

    }
}

2. Thêm thẻ RecyclerView vào layout main và đặt ID

<?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"
    tools:context=".MainActivity">


    <androidx.recyclerview.widget.RecyclerView

        android:id="@+id/recyclerview01"

        android:layout_width="match_parent"

        android:layout_height="match_parent"/>


<androidx.constraintlayout.widget.ConstraintLayout>

Chú ý: Có thể gắn luôn layoutmanager cho recyclerview ở layout thì trong code java không cần set layoutmanager

LayoutManager có thể dùng loại GridLayout hoặc LinearLayout. Code dưới đây là dùng GridLayout

<androidx.recyclerview.widget.RecyclerView

    android:id="@+id/rc01"

    android:layout_width="match_parent"

    android:layout_height="300dp"

    app:layout_constraintEnd_toEndOf="parent"

    app:layout_constraintStart_toStartOf="parent"

    app:layout_constraintTop_toBottomOf="@+id/button"

    app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"

    app:spanCount="2"

    />

Dùng gridLayout thì có thêm spanCount để chia cột, dùng linear thì có thêm orientaion

<androidx.recyclerview.widget.RecyclerView

    android:id="@+id/rc01"

    android:layout_width="match_parent"

    android:layout_height="300dp"

    app:layout_constraintEnd_toEndOf="parent"

    app:layout_constraintStart_toStartOf="parent"

    app:layout_constraintTop_toBottomOf="@+id/button"

    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"

    android:orientation="horizontal"

    />

Ở dạng LinearLayout: Nếu để horizon.. thì cần chú ý thuộc tính width của item 

3. Tạo layout custom cho từng phần tử

Bạn cần chú ý thuộc tính  android:layout_height="wrap_content" , nếu để mặc định sẽ là match_parent  lúc đó giao diện chỉ nhìn thấy 1 dòng

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:background="#ccc"

    android:layout_margin="10dp">

    <TextView

        android:id="@+id/tv_id"

        android:textColor="#BC3636"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"/>


    <TextView

        android:id="@+id/tv_name"

        android:textColor="#2196F3"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"/>

<LinearLayout>

4. Tạo class loại ViewHolder  (Có thể viết class này vào trong class SanPhamAdapter, lúc đó class này sẽ là một thuộc tính của SanPhamAdapter)

Lớp SanPhamViewHolder có tác dụng để ánh xạ các view của một dòng

import android.view.View;

import android.widget.TextView;

import androidx.annotation.NonNull;

import androidx.recyclerview.widget.RecyclerView;

public class SanPhamViewHolder extends RecyclerView.ViewHolder {

    public TextView tv_id;

    public TextView tv_name;

    public SanPhamViewHolder(@NonNull View itemView) {

        super(itemView);

        tv_id = itemView.findViewById(R.id.tv_id);

        tv_name = itemView.findViewById(R.id.tv_name)

    }

}

5. Tạo Adapter: Sử dụng Adapter của lớp RecyclerView và phải truyền vào kiểu cấu trúc của phần từng phần tử đó là SanPhamViewHolder

 Chú ý phần kế thừa đúng lớp adapter của RecyclerView, tránh nhầm lẫn với BaseAdapter

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import androidx.annotation.NonNull;

import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;


public class SanPhamAdapter extends RecyclerView.Adapter<SanPhamViewHolder>{

    Context context;

    ArrayList<SanPham> listSP;

    // hàm khởi tạo để truyền vào context và danh sách sản phẩm

    public SanPhamAdapter(ArrayList<SanPham> ds ){
  
        this.listSP = ds;

    }


    ///onCreateViewHolder hàm khởi tạo layout cho recyclerview

    @NonNull
    @Override  // hàm khởi tạo layout của một dòng

    public SanPhamViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        this.context = parent.getContext(); // gán vào thuộc tính context để dùng nhiều lần
      
        LayoutInflater inflater = LayoutInflater.from(context); 

        View view_of_item = inflater.inflate(R.layout.custom_item, parent,false);  // gắn layout custom cho item, xem ở bước 5

        SanPhamViewHolder sanPhamViewHolder = new SanPhamViewHolder(view_of_item); 

        return sanPhamViewHolder;  //return lại để hàm onBind bên dưới có dữ liệu làm việc
    }


    
    @Override // hàm dùng custom lại cách gắn dữ liệu cho viewholder
    public void onBindViewHolder(@NonNull SanPhamViewHolder holder, int position) {

        SanPham sp  = listSP.get(position);

        holder.tv_id.setText(sp.id +"");
        holder.tv_name.setText(sp.name);

    }


    @Override
    public int getItemCount() {
        return listSP.size();  // chú ý return size để có số lượng dòng
    }
}

6. Gọi adapter trong activity

Lưu ý các gói import phải đúng loại Adapter, tránh nhầm lẫn

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        recyclerView = findViewById(R.id.recyclerview01); // ánh xạ view vào biến

        // dùng đối tượng layout manager để quản lý
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);



        //--- Tạo dữ liệu: Phần này bạn có thể sử dụng SQLite để lấy dữ liệu đưa lên một ArrayList

        SanPham sp = new SanPham(1,"Điện thoại");

        ArrayList<SanPham> list = new ArrayList<SanPham>();
        list.add(sp);

        SanPham sp2 = new SanPham(2,"Điện thoại 2222");
        list.add(sp2);

        SanPham sp3 = new SanPham(3,"Điện thoại 33333");
        list.add(sp3);

        // tạo adapter và gắn adapter cho recyclerView
        SanPhamAdapter sanPhamAdapter = new SanPhamAdapter(list);
        recyclerView.setAdapter(sanPhamAdapter);

    }

}

 

Lab thực hành thêm:

Dùng SQLite tạo bảng user gồm các cột: id, name, avatar (cột này để lưu tên ảnh trong resource), copy tạm vài cái ảnh vào thư mục drawable để làm demo.

Sử dụng lệnh sql chèn sẵn ít nhất 5 bản ghi vào csdl

Viết giao diện sử dụng recyclerview  hiển thị danh sách user với 2 hình thức: lưới và hình thức danh sách. Tự trình bày hiển thị của từng phần tử.

 

Nguồn: zezo.dev