Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 리사이클러뷰(RecyclerView) 완벽 가이드 – 학생 명부 앱 만들기

안드로이드 RecyclerView란?

RecyclerView(리사이클러뷰)는 ListView의 더 발전된 버전으로, ViewHolder 디자인 패턴을 기반으로 동작합니다. RecyclerView를 활용하면 그리드(Grid) 형태와 리스트(List) 형태의 아이템을 모두 손쉽게 표시할 수 있으며, 대량의 데이터를 스크롤할 때도 뛰어난 성능을 발휘합니다.

이 글에서는 학생의 이름과 나이를 표시하는 학생 기록 앱을 직접 만들어 보면서 RecyclerView를 프로젝트에 통합하는 전 과정을 단계별로 살펴보겠습니다.


1단계 – 새 프로젝트 생성

Android Studio에서 File → New Project로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 새 프로젝트를 만듭니다.

2단계 – build.gradle에 RecyclerView 종속성 추가

build.gradle 파일을 열고 RecyclerView 라이브러리 의존성을 추가합니다.

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'
}

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을 부모 레이아웃으로 사용하여 화면에 RecyclerView를 배치했습니다. 세로 스크롤바(android: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.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
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 LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        recyclerView.setAdapter(studentAdapter);
        StudentDataPrepare();
    }
    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);
    }
}

위 코드에서는 RecyclerView와 StudentAdapter를 초기화했습니다. 어댑터에는 ArrayList 형태의 studentDataList를 전달하며, 이 리스트에는 각 학생의 이름(name)나이(age) 데이터가 담겨 있습니다. 또한 DividerItemDecoration을 적용해 항목 사이에 구분선이 표시되도록 했습니다.

5단계 – StudentAdapter.java 작성

수정된 src/StudentAdapter.java 파일의 내용은 다음과 같습니다.

package com.example.andy.tutorialspoint;
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.TextView;
import java.util.List;
class StudentAdapter extends RecyclerView.Adapter {
    List 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);
        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;
        public MyViewHolder(View itemView) {
            super(itemView);
            name=itemView.findViewById(R.id.name);
            age=itemView.findViewById(R.id.age);
        }
    }
}

어댑터 클래스는 다음 네 가지 핵심 요소로 구성됩니다.

  • onCreateViewHolder() – 뷰 홀더(ViewHolder)를 생성하고 해당 뷰를 반환합니다.
  • onBindViewHolder() – 생성된 뷰 홀더에 데이터를 바인딩합니다.
  • getItemCount() – 리스트의 전체 크기를 반환합니다.
  • MyViewHolder 클래스 – RecyclerView.ViewHolder를 상속받는 내부 클래스로, 각 항목의 뷰를 참조합니다.

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>

위 리스트 아이템 뷰에서는 가로 방향 LinearLayout 안에 이름(name)나이(age)를 표시할 두 개의 TextView를 weight 값을 활용해 좌우로 균등하게 배치했습니다.

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;
    }
}

위 코드는 학생의 이름과 나이를 담는 데이터 객체(Data Model)를 정의합니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭하세요. 실행할 기기 목록에서 본인의 모바일 기기를 선택하면, 앱이 설치되고 아래와 같은 기본 화면이 표시됩니다.

안드로이드 리사이클러뷰(RecyclerView) 완벽 가이드 – 학생 명부 앱 만들기

화면을 아래로 스크롤하면 나머지 학생 목록이 다음과 같이 표시됩니다.

안드로이드 리사이클러뷰(RecyclerView) 완벽 가이드 – 학생 명부 앱 만들기