การทำงานกับ Card View และ Recycler View ใน Android
ก่อนจะเข้าสู่ตัวอย่าง Card View สำหรับ Recycler View เราควรทราบก่อนว่า Recycler View ใน Android คืออะไร Recycler View เป็นเวอร์ชันขั้นสูงของ List View และทำงานตามรูปแบบการออกแบบ View Holder โดยใช้ Recycler View เราสามารถแสดงกริดและรายการไอเท็มได้
Card View ขยายมาจาก Frame Layout และใช้แสดงไอเท็มในรูปแบบการ์ด รองรับรัศมีมุมและเงาเป็นแท็กที่กำหนดไว้ล่วงหน้า
ตัวอย่างนี้สาธิตวิธีการรวม Recycler View กับ Card View โดยสร้างแอปบันทึกนักเรียนที่สวยงามซึ่งแสดงชื่อนักเรียนพร้อมอายุ
ขั้นตอนที่ 1 - สร้างโปรเจกต์ใหม่ใน Android Studio
ไปที่ File → New Project และกรอกรายละเอียดที่จำเป็นทั้งหมดเพื่อสร้างโปรเจกต์ใหม่
ขั้นตอนที่ 2 - เพิ่มการอ้างอิงไลบรารี Recycler View และ Card View ใน build.gradle
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'
}
ขั้นตอนที่ 3 - เพิ่มโค้ดใน 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="vertical" />
</RelativeLayout>
ในโค้ดด้านบน เราได้เพิ่ม Recycler View เข้ากับ Window Manager โดยใช้ Relative Layout เป็นพาเรนต์เลย์เอาต์
ขั้นตอนที่ 4 - เพิ่มโค้ดใน 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 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<StudentData> 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);
RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(manager);
recyclerView.setAdapter(studentAdapter);
prepareStudentData();
}
@RequiresApi(api = Build.VERSION_CODES.N)
private void prepareStudentData() {
StudentData data = new StudentData("sai", 25);
studentDataList.add(data);
data = new StudentData("sai", 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<StudentData>() {
@Override
public int compare(StudentData o1, StudentData o2) {
return o1.name.compareTo(o2.name);
}
});
}
}
ในโค้ดด้านบน เราได้เพิ่ม Recycler View และ StudentAdapter โดยส่ง studentDataList เป็น ArrayList ซึ่งมีข้อมูลชื่อและอายุของนักเรียน
เพื่อให้ได้กริด เราต้องใช้ Grid Layout Manager ดังนี้:
RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2);
ในโค้ดด้านบน เราใช้ Layout Manager เป็น GridLayoutManager และเพิ่มเซลล์เป็น 2 ดังนั้นจะแสดงผล 2 กริดในแต่ละแถว
เพื่อเปรียบเทียบไอเท็ม Recycler View เราใช้เฟรมเวิร์ก Collections และเมธอด sort ดังนี้:
Collections.sort(studentDataList, new Comparator<StudentData>() {
@Override
public int compare(StudentData o1, StudentData o2) {
return o1.name.compareTo(o2.name);
}
});
โค้ดด้านบนเปรียบเทียบองค์ประกอบโดยใช้ชื่อ
ขั้นตอนที่ 5 - เนื้อหาไฟล์ 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<StudentAdapter.MyViewHolder> {
List<StudentData> studentDataList;
public StudentAdapter(List<StudentData> 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);
}
}
}
ในคลาส Adapter มีเมธอดหลัก 4 เมธอด ดังนี้:
- onCreateViewHolder() - ใช้สร้าง ViewHolder และคืนค่า View
- onBindViewHolder() - ผูกข้อมูลกับ ViewHolder ที่สร้างไว้
- getItemCount() - คืนค่าจำนวนไอเท็มในรายการ
- MyViewHolder class - คลาสภายใน ViewHolder ที่ขยายมาจาก RecyclerView.ViewHolder
เพื่อกำหนดพื้นหลังสุ่มให้ไอเท็ม Recycler View เราสร้างสีสุ่มโดยใช้คลาส Random และกำหนดสีให้พาเรนต์ของไอเท็ม View ดังนี้:
Random rnd = new Random();
int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
viewHolder.parent.setBackgroundColor(currentColor);
ขั้นตอนที่ 6 - เนื้อหาไฟล์ 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>
ในมุมมองไอเท็มรายการด้านบน เราสร้าง TextView สองตัวสำหรับชื่อและอายุภายใน CardView Card View มีคุณสมบัติรัศมีมุมและเงาที่กำหนดไว้ล่วงหน้า ดังนั้นเราจึงใช้รัศมีมุมกับ Card View
ขั้นตอนที่ 7 - เนื้อหาไฟล์ src/StudentData.java
package com.example.andy.tutorialspoint;
class StudentData {
String name;
int age;
public StudentData(String name, int age) {
this.name = name;
this.age = age;
}
}
โค้ดด้านบนเป็นคลาสโมเดลข้อมูลนักเรียน ลองรันแอปพลิเคชันของคุณ สมมติว่าคุณเชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์แล้ว เพื่อรันแอปจาก Android Studio ให้เปิดไฟล์กิจกรรมของโปรเจกต์หนึ่งและคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณเป็นตัวเลือก และตรวจสอบอุปกรณ์ซึ่งจะแสดงหน้าจอเริ่มต้น

ตอนนี้เลื่อนลง RecyclerView จะแสดงผลลัพธ์ดังภาพด้านล่าง
