Custom Dòng Dữ Liệu Của RecyclerView Trong Android

Xin chào các bạn, hôm nay mình sẽ giới thiệu về lập trình android tổng quan và cách custom lại dòng dữ liệu trong Recyclerview. Các bạn cùng theo dõi nha

Recyclerview là gì?

RecyclerView là một ViewGroup nó được dùng để chuẩn bị và hiển thị các View tương tự nhau. RecyclerView được cho là sự kế thừa của ListView và GridView. Ưu điểm nổi trội của RecyclerView là nó có khả năng mở rộng tốt hơn, nó có thể hiển thị dữ liệu linh hoạt  theo cả chiều ngang và chiều dọc, cải thiện hiệu năng so với listview .

Khi sử dụng recyclerview android ta cần có:

Recyclerview.Adapter: Quản lý và cập nhật dữ liệu hiển thị vào View trong phần  tử của recyclerview,khi tạo custom Adapter chúng ta phải override lại hai phương thức chính là:

  • onCreateViewHolder: Phương thức dùng để tạo view mới cho RecyclerView.
  • onBindViewHolder: Phương thức này dùng để gắn data và ánh xạ view.

RecyclerView.LayoutManager: Lớp mà để quy định cách mà vị trí các phần tử trong RecyclerView hiện thị, có thể sử dụng các lớp kế thừa LinearLayoutManager, GridLayoutManager, StaggerdGridLayoutManager.

  • LinearLayoutManager : Các item của recyclerview sẽ scroll theo chiều dọc.
  • GridLayoutManager: Các item của recyclerview sẽ hiển thị với dạng gird như GirdView.
  • StaggerdGridLayoutManager: Các item của recyclerview sẽ hiển thị với dạng gird so le.

RecyclerView.ItemAnimator: Lớp để xây dựng hiệu ứng cho các sự kiện trên phần tử hiển thị, như hiệu ứng khi thêm phần tử vào, xóa  phần tử khỏi RecyclerView.

Trong bài viết này mình sẽ hướng dẫn các bạn cách custom dòng dữ liệu của recyclerview scroll theo chiều dọc nhé  !

Đầu tiên các bạn mở android studio tạo project trong android studio bằng cách click vào menu File ->New -> New Project… sau đó một hộp thoại sẽ hiện lên và chọn Empty Activity và nhấn Next nhé.

 

Sau đó đặt tên cho project của mình, phần Package name mình để nguyên, Save seclection là đường dẫn lưu project để tùy ý nhé , Language mình chọn java, Minimun SDK mình để API 16: Android 4.1( Jelly Bean) để các thiết bị phiên bản thấp có thể cài được ứng dụng của mình rồi nhấn Finish.

Sau khi tạo xong project đầu tiên ta thêm gói support của meterial design vào android studio, vì mặc định recyclerview không có sẵn trong android SDK vậy nên chúng ta sẽ thêm gói support của meterial design vào file build.gradle của app module và nhấn sync now để android studio download thư viện về như hình dưới nhé :

    implementation 'com.android.support:design:29.1.0'

Tạo class model có tên là SanPham để chứa data.

public class SanPham {
    private String tenSanPham;
    private double GiaSanPham;
    private int hinhSanPham;

    public SanPham(String tenSanPham, double giaSanPham, int hinhSanPham) {
        this.tenSanPham = tenSanPham;
        GiaSanPham = giaSanPham;
        this.hinhSanPham = hinhSanPham;
    }

    public String getTenSanPham() {
        return tenSanPham;
    }

    public void setTenSanPham(String tenSanPham) {
        this.tenSanPham = tenSanPham;
    }

    public double getGiaSanPham() {
        return GiaSanPham;
    }

    public void setGiaSanPham(double giaSanPham) {
        GiaSanPham = giaSanPham;
    }

    public int getHinhSanPham() {
        return hinhSanPham;
    }

    public void setHinhSanPham(int hinhSanPham) {
        this.hinhSanPham = hinhSanPham;
    }
}

Tạo item của reyclerview : item_view.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:padding="5dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
<ImageView
    android:id="@+id/imgAvatar"
    android:scaleType="fitXY"
    android:src="@drawable/iphone_11"
    android:layout_width="70dp"
    android:layout_height="75dp"/>
    <LinearLayout
        android:orientation="vertical"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@id/imgAvatar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView
            android:text="Iphone 11"
            android:textSize="16dp"
            android:textStyle="bold"
            android:textColor="#00AC47"
            android:id="@+id/txtTenSanPham"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <TextView
            android:text="11000000 vnd"
            android:textSize="15dp"
            android:textColor="#676767"
            android:id="@+id/txtGiaSanPham"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>
    <ImageView
        android:layout_centerVertical="true"
        android:layout_marginRight="10dp"
        android:src="@drawable/icon_add"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <View
        android:layout_marginTop="5dp"
        android:background="#E6E6E6"
        android:layout_below="@id/imgAvatar"
        android:layout_width="match_parent"
        android:layout_height="1dp"/>
</RelativeLayout>

Viết mã cho layout trong activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="#fff"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <EditText
        android:id="@+id/edtSearch"
        android:layout_toLeftOf="@id/soft"
        android:layout_marginTop="10dp"
        android:background="@drawable/custom_edt"
        android:hint="Nhập tên sản phẩm cần tìm"
        android:padding="10dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:drawableLeft="@drawable/ic_search_grey"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <ImageView
        android:id="@+id/soft"
        android:layout_marginTop="10dp"
        android:layout_alignParentRight="true"
        android:src="@drawable/ic_sort_grey"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_marginTop="5dp"
        android:layout_below="@id/edtSearch"
        tools:listitem="@layout/item_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
       />

</RelativeLayout>

Tạo class SanPhamAdapter để custom dòng dữ liệu cho recyclerview

public class SanPhamAdapter extends RecyclerView.Adapter<SanPhamAdapter.ViewHolder> {
    Context context;
    ArrayList<SanPham> listSanPham;

    public SanPhamAdapter(Context context, ArrayList<SanPham> listSanPham) {
        this.context = context;
        this.listSanPham = listSanPham;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // gán view
        View view = LayoutInflater.from(context).inflate(R.layout.item_view, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        // Gán dữ liêuk
        SanPham sanPham = listSanPham.get(position);
        holder.txtTenSanPham.setText(sanPham.getTenSanPham());
        Locale locale = new Locale("vn", "VN");
        NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
        holder.txtGiaSanPham.setText(currencyFormatter.format(sanPham.getGiaSanPham()));
        holder.imgAvatar.setImageResource(sanPham.getHinhSanPham());
    }

    @Override
    public int getItemCount() {
        return listSanPham.size(); // trả item tại vị trí postion
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imgAvatar;
        TextView txtTenSanPham, txtGiaSanPham;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // Ánh xạ view
            imgAvatar = itemView.findViewById(R.id.imgAvatar);
            txtGiaSanPham = itemView.findViewById(R.id.txtGiaSanPham);
            txtTenSanPham = itemView.findViewById(R.id.txtTenSanPham);

        }
    }
}

Viết mã Cho MainActivity.

public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<SanPham > listSanPham;
SanPhamAdapter sanPhamAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView=findViewById(R.id.recyclerview);
        listSanPham=new ArrayList<>();
        listSanPham.add(new SanPham("Xiaomi Mi 10",12000000,R.drawable.xiaomi_mi10));
        listSanPham.add(new SanPham("Iphone X",19000000,R.drawable.iphonex));
        listSanPham.add(new SanPham("Iphone 11",23000000,R.drawable.iphone_11));
        listSanPham.add(new SanPham("Xiaomi black shark 3",14000000,R.drawable.black_sharp3));
        listSanPham.add(new SanPham("Samsung galaxy s10",14000000,R.drawable.galaxy_s10));
        listSanPham.add(new SanPham("Oppo reno 3",10000000,R.drawable.oppo));
        listSanPham.add(new SanPham("Samsung note 10",14000000,R.drawable.samsungnote10));
        listSanPham.add(new SanPham("Iphone 8",17000000,R.drawable.iphone8));
        sanPhamAdapter=new SanPhamAdapter(getApplicationContext(),listSanPham);
        recyclerView.setAdapter(sanPhamAdapter);
    }
}

Thành quả

Cuối cùng ta chạy ứng dụng và xem kết quả nhé ! Hiển thị như hình dưới là các bạn đã  thành công !

Lưu ý các bạn không nhất thiết phải làm giống mình nhé ! Các bạn có thể thay hình, đổi bố cục, màu chữ tùy các bạn.

Cảm ơn các bạn đã đọc bài !