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

안드로이드 카드뷰(CardView)와 리사이클러뷰(RecyclerView) 완벽 가이드

카드뷰와 리사이클러뷰란 무엇인가?

리사이클러뷰(RecyclerView)는 안드로이드의 리스트뷰(ListView)보다 발전된 형태의 뷰로, 뷰홀더(ViewHolder) 디자인 패턴을 기반으로 동작합니다. 리사이클러뷰를 사용하면 그리드 형태와 리스트 형태의 아이템을 모두 효율적으로 표시할 수 있습니다.

카드뷰(CardView)는 프레임 레이아웃(FrameLayout)을 확장한 뷰로, 아이템을 카드 형태로 보여주기 위해 사용됩니다. 미리 정의된 속성 태그를 통해 모서리 둥글기(radius)와 그림자(shadow) 효과를 손쉽게 적용할 수 있습니다.

이번 예제에서는 학생 이름과 나이를 카드 형태로 보여주는 학생 정보 앱을 만들면서 리사이클러뷰와 카드뷰를 통합하는 방법을 단계별로 알아보겠습니다.

프로젝트 설정 및 라이브러리 추가

1단계 − 안드로이드 스튜디오에서 새 프로젝트를 생성합니다. File ⇒ New Project 메뉴로 이동한 후, 필요한 모든 정보를 입력하여 프로젝트를 만듭니다.

2단계 − 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>

위 코드에서는 상대 레이아웃(RelativeLayout)을 부모 레이아웃으로 사용하여 리사이클러뷰를 화면에 추가했습니다.

메인 액티비티 구현

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);
        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를 연결했습니다. 어댑터에는 학생 이름과 나이가 담긴 studentDataList(ArrayList)를 전달했습니다.

그리드 레이아웃 매니저 설정

화면을 그리드 형태로 구성하려면 아래와 같이 그리드 레이아웃 매니저(GridLayoutManager)를 사용해야 합니다.

RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2);

위 코드에서는 레이아웃 매니저를 그리드 레이아웃 매니저로 지정하고 열(column) 수를 2로 설정했습니다. 따라서 한 줄에 두 개의 그리드 셀이 표시됩니다.

리스트 데이터 정렬하기

리사이클러뷰의 아이템을 정렬하기 위해 컬렉션 프레임워크의 sort 메서드를 아래와 같이 사용했습니다.

Collections.sort(studentDataList, new Comparator() {
    @Override
    public int compare(studentData o1, studentData o2) {
        return o1.name.compareTo(o2.name);
    }
});

위 코드는 학생 데이터를 이름(name) 기준으로 비교하여 오름차순으로 정렬합니다.

어댑터(Adapter) 클래스 작성

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 {
    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);
        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() : 뷰홀더를 생성하고 해당 뷰를 반환하는 메서드입니다.

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단계 − 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>

위 리스트 아이템 뷰에서는 카드뷰 안에 이름과 나이를 표시하는 두 개의 텍스트뷰를 배치했습니다. 카드뷰는 기본적으로 모서리 둥글기(cornerRadius)와 그림자(shadow) 속성을 제공하므로, 여기서는 cardCornerRadius 속성을 활용해 부드러운 카드 디자인을 구현했습니다.

학생 데이터 모델 클래스

7단계 − src/studentData.java 파일의 수정된 내용은 다음과 같습니다.

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

위 코드는 학생의 이름과 나이 정보를 담는 데이터 객체를 정의한 것입니다.

앱 실행 및 결과 확인

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

안드로이드 카드뷰(CardView)와 리사이클러뷰(RecyclerView) 완벽 가이드

리사이클러뷰를 아래로 스크롤하면 다음과 같이 각 카드마다 서로 다른 랜덤 배경색이 적용된 결과를 확인할 수 있습니다.

안드로이드 카드뷰(CardView)와 리사이클러뷰(RecyclerView) 완벽 가이드