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

안드로이드 앱에서 리사이클러뷰(RecyclerView) 사용하기 – 단계별 완전 가이드

개요

이 예제에서는 안드로이드 앱에서 RecyclerView(리사이클러뷰)를 사용해 목록 형태의 데이터를 화면에 표시하는 방법을 단계별로 살펴봅니다. RecyclerView는 ListView보다 뛰어난 성능과 유연성을 제공하는 안드로이드의 대표적인 목록 위젯으로, 대량의 데이터를 스크롤 가능한 리스트로 보여줄 때 가장 널리 사용됩니다.

여기서는 영화 제목, 장르, 개봉 연도를 카드 형태로 나열하는 간단한 영화 목록 앱을 만들어 보겠습니다.

1단계 – 새 프로젝트 생성

Android Studio에서 File ⇒ New Project를 선택하고, 새 프로젝트 생성에 필요한 모든 정보를 입력해 프로젝트를 만듭니다.

참고: RecyclerView와 CardView를 사용하려면 build.gradle 파일에 다음 의존성이 포함되어 있어야 합니다.
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation 'androidx.cardview:cardview:1.0.0'

2단계 – activity_main.xml 작성

다음 코드를 res/layout/activity_main.xml에 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
   android:id="@+id/rlMain"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="16dp"
   android:orientation="vertical">
   <androidx.recyclerview.widget.RecyclerView
      android:id="@+id/recyclerView"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />
</LinearLayout>

3단계 – MainActivity.java 작성

다음 코드를 src/MainActivity.java에 추가합니다. 여기서는 RecyclerView에 레이아웃 매니저와 어댑터를 연결하고, 샘플 영화 데이터를 준비합니다.

package app.com.sample;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
   private List<MovieModel> movieList = new ArrayList<>();
   private MoviesAdapter mAdapter;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      RecyclerView recyclerView = findViewById(R.id.recyclerView);
      mAdapter = new MoviesAdapter(movieList);
      LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
      recyclerView.setLayoutManager(mLayoutManager);
      recyclerView.setItemAnimator(new DefaultItemAnimator());
      recyclerView.setAdapter(mAdapter);
      prepareMovieData();
   }
   private void prepareMovieData() {
      MovieModel movie = new MovieModel("Mad Max: Fury Road", "Action & Adventure", "2015");
      movieList.add(movie);
      movie = new MovieModel("Inside Out", "Animation, Kids & Family", "2015");
      movieList.add(movie);
      movie = new MovieModel("Star Wars: Episode VII - The Force Awakens", "Action", "2015");
      movieList.add(movie);
      movie = new MovieModel("Shaun the Sheep", "Animation", "2015");
      movieList.add(movie);
      movie = new MovieModel("The Martian", "Science Fiction & Fantasy", "2015");
      movieList.add(movie);
      movie = new MovieModel("Mission: Impossible Rogue Nation", "Action", "2015");
      movieList.add(movie);
      movie = new MovieModel("Up", "Animation", "2009");
      movieList.add(movie);
      movie = new MovieModel("Star Trek", "Science Fiction", "2009");
      movieList.add(movie);
      movie = new MovieModel("The LEGO MovieModel", "Animation", "2014");
      movieList.add(movie);
      movie = new MovieModel("Iron Man", "Action & Adventure", "2008");
      movieList.add(movie);
      movie = new MovieModel("Aliens", "Science Fiction", "1986");
      movieList.add(movie);
      movie = new MovieModel("Chicken Run", "Animation", "2000");
      movieList.add(movie);
      movie = new MovieModel("Back to the Future", "Science Fiction", "1985");
      movieList.add(movie);
      movie = new MovieModel("Raiders of the Lost Ark", "Action & Adventure", "1981");
      movieList.add(movie);
      movie = new MovieModel("Goldfinger", "Action & Adventure", "1965");
      movieList.add(movie);
      movie = new MovieModel("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014");
      movieList.add(movie);
      mAdapter.notifyDataSetChanged();
   }
}

4단계 – MovieModel.java 작성

목록에 표시할 데이터를 담을 모델 클래스입니다. 다음 코드를 src/MovieModel.java에 추가합니다.

package app.com.sample;
public class MovieModel {
   private String title, genre, year;
   public MovieModel() {
   }
   public MovieModel(String title, String genre, String year) {
      this.title = title;
      this.genre = genre;
      this.year = year;
   }
   public String getTitle() {
      return title;
   }
   public void setTitle(String name) {
      this.title = name;
   }
   public String getYear() {
      return year;
   }
   public void setYear(String year) {
      this.year = year;
   }
   public String getGenre() {
      return genre;
   }
   public void setGenre(String genre) {
      this.genre = genre;
   }
}

5단계 – movies_list.xml 작성

리스트의 각 항목이 어떻게 보일지 정의하는 레이아웃입니다. 다음 코드를 res/layout/movies_list.xml에 추가합니다. 각 항목은 CardView로 감싸져 있어 입체적인 카드 느낌을 줍니다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="https://schemas.android.com/apk/res/android"
   android:layout_width=" match_parent"
   android:layout_height="100dp"
   android:layout_margin="8dp">
   <RelativeLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:padding="8dp">
      <TextView
         android:id="@+id/title"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_alignParentStart="true"
         android:layout_toStartOf="@+id/year"
         android:textColor="#222222"
         android:textSize="16sp"
         android:textStyle="bold" />
      <TextView
         android:id="@+id/year"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentEnd="true"
         android:textColor="#999999" />
      <TextView
         android:id="@+id/genre"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_alignParentBottom="true" />
   </RelativeLayout>
</androidx.cardview.widget.CardView>

6단계 – MoviesAdapter.java 작성

어댑터는 데이터 목록과 RecyclerView 사이를 연결하는 역할을 합니다. 다음 코드를 src/MoviesAdapter.java에 추가합니다.

package app.com.sample;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {
   private List<MovieModel> moviesList;
   class MyViewHolder extends RecyclerView.ViewHolder {
      TextView title, year, genre;
      MyViewHolder(View view) {
         super(view);
         title = view.findViewById(R.id.title);
         genre = view.findViewById(R.id.genre);
         year = view.findViewById(R.id.year);
      }
   }
   public MoviesAdapter(List<MovieModel> moviesList) {
      this.moviesList = moviesList;
   }
   @NonNull
   @Override
   public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
      View itemView = LayoutInflater.from(parent.getContext())
      .inflate(R.layout.movie_list, parent, false);
      return new MyViewHolder(itemView);
   }
   @Override
   public void onBindViewHolder(MyViewHolder holder, int position) {
      MovieModel movie = moviesList.get(position);
      holder.title.setText(movie.getTitle());
      holder.genre.setText(movie.getGenre());
      holder.year.setText(movie.getYear());
   }
   @Override
   public int getItemCount() {
      return moviesList.size();
   }
}

7단계 – AndroidManifest.xml 확인

다음 코드를 androidManifest.xml에 추가하거나 기존 내용과 비교해 확인합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

앱 실행하기

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

안드로이드 앱에서 리사이클러뷰(RecyclerView) 사용하기 – 단계별 완전 가이드