Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Xây dựng Horizontal ListView với RecyclerView trong Android

Trước khi đi vào ví dụ, chúng ta nên biết RecyclerView là gì trong Android. RecyclerView là phiên bản nâng cao của ListView và hoạt động dựa trên View Holder design pattern. Sử dụng RecyclerView chúng ta có thể hiển thị lưới và danh sách item.

Ví dụ này minh họa cách xây dựng Horizontal ListView với RecyclerView bằng cách tạo ứng dụng hồ sơ sinh viên hiển thị tên và tuổi.

Bước 1

Tạo một dự án mới trong Android Studio, vào File → New Project và điền đầy đủ thông tin cần thiết để tạo dự án mới.

Bước 2

Mở build.gradle và thêm dependency RecyclerView & CardView.

apply plugin: 'com.android.application' android {    compileSdkVersion 28    defaultConfig {       applicationId "com.example.andy.tutorialspoint"       minSdkVersion 19       targetSdkVersion 28       versionCode 1       versionName "1.0"       testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"    }    buildTypes {       release {          minifyEnabled false          proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'       }    } } dependencies {    implementation fileTree(dir: 'libs', include: ['*.jar'])    implementation 'com.android.support:appcompat-v7:28.0.0'    implementation 'com.android.support:design:28.0.0'    implementation 'com.android.support.constraint:constraint-layout:1.1.3'    implementation 'com.android.support:cardview-v7:28.0.0'    implementation 'com.android.support:recyclerview-v7:28.0.0'    testImplementation 'junit:junit:4.12'    androidTestImplementation 'com.android.support.test:runner:1.0.2'    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' }

Bước 3

Thêm mã sau vào res/layout/activity_main.xml.

<?xml version = "1.0" encoding = "utf-8"?> <RelativeLayout    xmlns:android = "https://schemas.android.com/apk/res/android"    xmlns:tools = "https://schemas.android.com/tools"    xmlns:app = "https://schemas.android.com/apk/res-auto"    android:layout_width = "match_parent"    android:layout_height = "match_parent"    app:layout_behavior = "@string/appbar_scrolling_view_behavior"    tools:showIn = "@layout/activity_main"    tools:context = ".MainActivity">    <android.support.v7.widget.RecyclerView       android:id = "@+id/recycler_view"       android:layout_width = "match_parent"       android:layout_height = "wrap_content"       android:scrollbars = "horizontal" /> </RelativeLayout>

Trong mã trên, chúng ta thêm RecyclerView vào Window Manager làm RelativeLayout cha và gán Horizontal scroll bars để cuộn theo chiều ngang.

Bước 4

Thêm mã sau vào src/MainActivity.java

package com.example.andy.tutorialspoint; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class MainActivity extends AppCompatActivity {    private RecyclerView recyclerView;    private StudentAdapter studentAdapter;    private List studentDataList = new ArrayList<>();    @TargetApi(Build.VERSION_CODES.O)    @Override    protected void onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);       setContentView(R.layout.activity_main);       recyclerView = findViewById(R.id.recycler_view);       studentAdapter = new StudentAdapter(studentDataList,MainActivity.this);       RecyclerView.LayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false);       recyclerView.setLayoutManager(manager);       recyclerView.setAdapter(studentAdapter);       StudentDataPrepare();    }    @RequiresApi(api = Build.VERSION_CODES.N)    private void StudentDataPrepare() {       studentData data = new studentData("sai", 25);       studentDataList.add(data);       data = new studentData("sai raj", 25);       studentDataList.add(data);       data = new studentData("raghu", 20);       studentDataList.add(data);       data = new studentData("raj", 28);       studentDataList.add(data);       data = new studentData("amar", 15);       studentDataList.add(data);       data = new studentData("bapu", 19);       studentDataList.add(data);       data = new studentData("chandra", 52);       studentDataList.add(data);       data = new studentData("deraj", 30);       studentDataList.add(data);       data = new studentData("eshanth", 28);       studentDataList.add(data);       Collections.sort(studentDataList, new Comparator() {          @Override          public int compare(studentData o1, studentData o2) {             return o1.name.compareTo(o2.name);          }       });    } }

Trong mã trên, chúng ta thêm RecyclerView và StudentAdapter. Trong StudentAdapter, chúng ta truyền studentDataList là ArrayList. StudentDataList chứa tên và tuổi sinh viên.

Để có Horizontal View, cần thêm layout params như dưới:

RecyclerView.LayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(manager);

Trong mã trên, chúng ta thêm LinearLayoutManager và vị trí cuộn là Horizontal nên nó sẽ cuộn theo chiều ngang.

Bước 5

Nội dung file src/StudentAdapter.java:

package com.example.andy.tutorialspoint; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import java.util.Random; class StudentAdapter extends RecyclerView.Adapter {    List<studentData> studentDataList;    public StudentAdapter(List studentDataList) {       this.studentDataList = studentDataList;    }    @NonNull    @Override    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {       View itemView = LayoutInflater.from(viewGroup.getContext())       .inflate(R.layout.student_list_row, viewGroup, false);       return new MyViewHolder(itemView);    }    @Override    public void onBindViewHolder(MyViewHolder viewHolder, int i) {       studentData data = studentDataList.get(i);       Random rnd = new Random();       int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));       viewHolder.parent.setBackgroundColor(currentColor);       viewHolder.name.setText(data.name);       viewHolder.age.setText(String.valueOf(data.age));    }    @Override    public int getItemCount() {       return studentDataList.size();    }    class MyViewHolder extends RecyclerView.ViewHolder {       TextView name,age;       LinearLayout parent;       public MyViewHolder(View itemView) {          super(itemView);          parent = itemView.findViewById(R.id.parent);          name = itemView.findViewById(R.id.name);          age = itemView.findViewById(R.id.age);       }    } }

Trong Adapter class có 4 phương thức:

  • onCreateViewHolder() – Tạo ViewHolder và trả về View.

  • onBindViewHolder() – Bind với ViewHolder đã tạo.

  • getItemCount() – Chứa kích thước list.

  • MyViewHolder class – Inner class ViewHolder kế thừa RecyclerView.ViewHolder.

Để đặt background ngẫu nhiên cho item RecyclerView, chúng ta tạo màu ngẫu nhiên dùng Random class và gán màu cho parent của view item như dưới:

Random rnd = new Random(); int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); viewHolder.parent.setBackgroundColor(currentColor);

Bước 6

Nội dung file xml res/layout/student_list_row.xml:

<?xml version = "1.0" encoding = "utf-8"?> <android.support.v7.widget.CardView xmlns:android = "https://schemas.android.com/apk/res/android"    xmlns:card_view = "https://schemas.android.com/apk/res-auto"    android:layout_width = "match_parent"    card_view:cardCornerRadius = "4dp"    android:id = "@+id/card_view"    android:layout_margin = "10dp"    android:layout_height = "200dp">    <LinearLayout       android:id = "@+id/parent"       android:layout_gravity = "center"       android:layout_width = "match_parent"       android:orientation = "vertical"       android:gravity = "center"       android:layout_height = "match_parent">       <TextView          android:id = "@+id/name"          android:layout_width = "wrap_content"          android:gravity = "center"          android:textSize = "25sp"          android:textColor = "#FFF"          android:layout_height = "wrap_content" />       <TextView          android:id = "@+id/age"          android:layout_width = "wrap_content"          android:gravity = "center"          android:textSize = "25sp"          android:textColor = "#FFF"          android:layout_height = "wrap_content" />    </LinearLayout> </android.support.v7.widget.CardView>

Trong view item trên, chúng ta tạo 2 TextView cho name và age bên trong CardView. CardView có sẵn corner radius và shadow. Vì vậy chúng ta dùng corner radius với CardView.

Bước 7

Nội dung file src/studentData.java:

class studentData {    String name;    int age;    public studentData(String name, int age) {       this.name = name;       this.age = age;    } }

Mã trên mô tả object student data. Hãy thử chạy ứng dụng. Giả sử bạn đã kết nối thiết bị Android thực tế với máy tính. Để chạy ứng dụng từ Android Studio, mở một file activity của dự án và nhấn biểu tượng Run từ thanh công cụ. Chọn thiết bị di động của bạn làm tùy chọn và kiểm tra thiết bị sẽ hiển thị màn hình mặc định:

Xây dựng Horizontal ListView với RecyclerView trong Android

Bây giờ cuộn ngang RecyclerView, kết quả như hình dưới:

Xây dựng Horizontal ListView với RecyclerView trong Android