RecyclerView란 무엇인가?
그리드 예제에 들어가기 전에 먼저 리사이클러뷰(RecyclerView)가 무엇인지 짚고 넘어가겠습니다. 리사이클러뷰는 기존 ListView(리스트뷰)의 발전된 버전으로, ViewHolder 디자인 패턴을 기반으로 동작합니다. 이 패턴 덕분에 화면에 보이지 않는 아이템의 뷰를 재활용할 수 있어 메모리 사용량이 줄고 스크롤 성능이 크게 향상됩니다. 리사이클러뷰를 사용하면 리스트 형태뿐 아니라 그리드 형태의 아이템도 손쉽게 표시할 수 있습니다.
이번 글에서는 학생의 이름과 나이를 그리드 형태로 보여주는 학생 명부 앱을 만들면서, 리사이클러뷰에 GridLayoutManager를 연동하는 방법을 단계별로 살펴보겠습니다.
1단계: 새 프로젝트 생성
안드로이드 스튜디오에서 File → New Project를 선택하고, 필요한 정보를 모두 입력해 새 프로젝트를 생성합니다.
2단계: build.gradle에 의존성 추가
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: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'
}참고로 최신 안드로이드 스튜디오 프로젝트라면 AndroidX 라이브러리를 사용하는 것이 좋습니다. 이 경우 androidx.recyclerview:recyclerview 의존성을 추가하면 됩니다.
3단계: activity_main.xml 레이아웃 작성
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>위 코드에서는 RelativeLayout을 부모 레이아웃으로 사용하고 그 안에 리사이클러뷰를 배치했습니다. 세로 스크롤바(scrollbars="vertical")를 활성화해 사용자가 스크롤 위치를 쉽게 파악할 수 있도록 했습니다.
4단계: MainActivity.java 작성
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 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.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
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", 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);
}
});
}
}위 코드에서는 리사이클러뷰와 StudentAdapter를 생성하고, 어댑터에 학생 데이터 리스트(ArrayList)를 전달했습니다. 각 데이터 항목은 학생의 이름과 나이를 담고 있습니다.
GridLayoutManager로 그리드 만들기
리사이클러뷰를 그리드 형태로 표시하려면 다음과 같이 GridLayoutManager를 사용해야 합니다.
RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2);
여기서 두 번째 인자인 2는 한 행에 표시할 열(column)의 개수를 의미합니다. 따라서 실행 결과에서는 한 줄에 두 개의 그리드 셀이 나타납니다.
Collections.sort()로 데이터 정렬
리사이클러뷰의 아이템을 정렬하기 위해 자바 컬렉션 프레임워크의 sort() 메서드를 다음과 같이 사용했습니다.
Collections.sort(studentDataList, new Comparator() {
@Override
public int compare(studentData o1, studentData o2) {
return o1.name.compareTo(o2.name);
}
});위 코드는 학생 데이터를 이름(name) 기준으로 오름차순 정렬합니다.
5단계: StudentAdapter.java 작성
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);
}
}
}어댑터 클래스에는 다음 네 가지 핵심 요소가 포함되어 있습니다.
onCreateViewHolder(): 뷰 홀더(ViewHolder)를 생성하고 해당 뷰를 반환합니다.
onBindViewHolder(): 생성된 뷰 홀더에 실제 데이터를 바인딩(연결)합니다.
getItemCount(): 표시할 리스트의 전체 개수를 반환합니다.
MyViewHolder 클래스: RecyclerView.ViewHolder를 상속하는 내부 클래스로, 각 아이템 뷰의 참조를 보관합니다.
랜덤 배경색 적용하기
각 그리드 아이템에 랜덤한 배경색을 적용하기 위해 안드로이드에서 기본 제공하는 Random 클래스로 임의 색상을 생성하고, 이를 아이템 뷰의 부모 레이아웃에 설정했습니다.
Random rnd = new Random(); int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); viewHolder.parent.setBackgroundColor(currentColor);
6단계: student_list_row.xml 작성
res/layout/student_list_row.xml 파일의 내용은 다음과 같습니다.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
android:orientation = "horizontal" android:layout_width="match_parent"
android:weightSum =" 1"
android:layout_height="wrap_content">
<TextView
android:id = "@+id/name"
android:layout_width = "0dp"
android:layout_weight = "0.5"
android:gravity = "center"
android:textSize = "15sp"
android:layout_height = "100dp" />
<TextView
android:id = "@+id/age"
android:layout_width = "0dp"
android:layout_weight = "0.5"
android:gravity = "center"
android:textSize = "15sp"
android:layout_height = "100dp" />
</LinearLayout>위 아이템 레이아웃에는 이름(name)과 나이(age)를 표시할 두 개의 TextView를 가로 방향으로 배치했습니다. layout_weight를 활용해 두 TextView가 각각 절반씩 공간을 차지하도록 구성했습니다.
7단계: studentData.java 모델 클래스 작성
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;
}
}위 클래스는 학생의 이름과 나이를 담는 단순한 데이터 객체(모델)입니다.
앱 실행하기
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰을 컴퓨터에 연결했다고 가정합니다. 안드로이드 스튜디오에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run(실행) 아이콘을 클릭하고, 기기 목록에서 본인의 모바일 기기를 선택하세요. 그러면 앱이 실행되며 다음과 같이 그리드 형태의 학생 명부가 화면에 표시됩니다.
