본문 바로가기
Android

RecyclerView 만들기

by holy season 2023. 4. 18.
반응형

RecyclerView란

2023.04.16 - [Android] - RecyclerView

 

RecyclerView

Android RecyclerView RecyclerView Android Jetpack의 구성요소 대량의 데이터 세트를 효율적으로 표시 개발자가 데이터를 제공하고 각 항목의 모양을 정의하면 RecyclerView 라이브러리가 필요할 때 요소를 동

holy-season.tistory.com

RecyclerView 구현 단계

RecyclerView를 구현하기 위해서는 다음과 같은 단계가 필요하다

  1. RecyclerView를 가진 xml 파일 작성
  2. RecyclerView에 넣을 xml 파일 작성
  3. RecyclerView의 레이아웃 매니저 생성 후 설정
  4. RecyclerViewAdapter 클래스 구현
  5. RecyclerViewAdapter 객체 생성 후 RecyclerView에 적용

RecyclerView 구현하기

RecyclerView를 가진 xml 파일 작성

기본적으로 주어지는 activity_main.xml에 RecyclerView를 생성한다

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />

</androidx.constraintlayout.widget.ConstraintLayout>

RecyclerView에 보여줄 xml 파일 작성

RecyclerView에 보여줄 xml 파일을 작성한다

xml 파일이름은 recycler_view_item.xml로 작성하였다

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/textView"
            android:layout_width="362dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Item1"
            android:textAlignment="center" />

        <Button
            android:id="@+id/button"
            android:layout_width="212dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Item1 Button" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

RecyclerView의 레이아웃 매니저 생성 후 설정

MainActivity 클래스에 activity_main.xml에 생성해 두었던 RecyclerView를 가져오고 RecyclerView.LayoutManager 클래스를 이용해 LinearLayoutManager 클래스를 생성한 후 가져온 RecyclerView에 만들어 두었던 RecyclerView.LayoutManager 객체를 적용한다.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
    }
}

RecyclerViewAdapter 클래스 구현

RecyclerViewAdapter 클래스 작성 및 ViewHolder 클래스 작성

RecyclerViewAdapter 클래스를 작성하고 내부 클래스로 ViewHolder 클래스를 작성한다.

ViewHolder 클래스는 Recycler.ViewHolder를 상속받고 RecyclerViewAdapter는 RecyclerView.Adapter <RecyclerViewAdaptor.ViewHolder>를 상속하게 한다

RecyclerView.Adapter의 제너릭 타입으로는 내부 클래스로 생성한 ViewHolder 이름을 적어야 한다.

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
        }
        
    }
}

ViewHolder 클래스 구현

ViewHolder 클래스는 recycler_view_item.xml에서 만들어 두었던 View들을 생성하는 역할을 한다

그러므로 View를 생성하도록 구현한다

    public static class ViewHolder extends RecyclerView.ViewHolder {

        TextView textView;
        Button button;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.textView);
            button = itemView.findViewById(R.id.button);
        }
    }

RecyclerViewAdapter 구현

RecyclerViewAdapter는 RecyclerView.Adapter를 상속받았기 때문에 onCreateViewHolder, onBindViewHolder, getItemCount 메서드를 구현해야 한다

onCreateViewHolder 메서드 구현

LayoutInflater 클래스를 사용해 부모 컨텍스트에 Recycler_view_item에 정의해 둔 View를 올려주는 코드를 작성한다

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.recycler_view_item, parent, false);
        return new ViewHolder(view);
    }

onBindViewHolder 메서드 구현

onBindViewHolder 메서드는 리스트나 배열에 저장해 두었던 값을 onCreateView로 만들었던 ViewHolder 객체에 데이터를 넣어주는 역할을 한다.

 

 

    List<String> list = new ArrayList<>();
    
    @Override
    public void onBindViewHolder(@NonNull  ViewHolder holder, int position) {
        holder.textView.setText(list.get(position));
        holder.button.setText(list.get(position));
    }

getItemCount 메서드 구현

getItemCount 메서드는 데이터를 저장하는 리스트나 배열의 크기를 반환하도록 구현해야 한다.

@Override
    public int getItemCount() {
        return list.size();
    }

RecyclerViewAdapter 객체 생성 후 RecyclerView에 적용

MainActivity 클래스에 돌아와서 작성해 두었던 코드 밑에 RecyclerViewAdapter 객체를 생성하고 recyclerView.setAdapter 메서드를 이용해 RecyclerViewAdapter를 적용한다

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter();
        recyclerView.setAdapter(recyclerViewAdapter);
    }
}

테스트

테스트하기 위해 RecyclerViewAdapter 클래스에 생성자를 이용해 list에 값을 50개 넣었다.

    public RecyclerViewAdapter() {
        for(int i=1; i<=50; i++) {
            list.add(String.format("Item%d", i));
        }
    }

결과

Item1에서 부터 Item50까지 recycler_view_item.xml에 정의해 둔 View들이 잘 나오는 것을 확인할 수 있었다.

전체 코드

클래스

더보기

MainActivity

package com.example.recyclerviewtest;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter();
        recyclerView.setAdapter(recyclerViewAdapter);
    }
}

RecyclerViewAdapter

package com.example.recyclerviewtest;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    List<String> list = new ArrayList<>();

    public RecyclerViewAdapter() {
        for(int i=1; i<=50; i++) {
            list.add(String.format("Item%d", i));
        }
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        TextView textView;
        Button button;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.textView);
            button = itemView.findViewById(R.id.button);
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.recycler_view_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull  ViewHolder holder, int position) {
        holder.textView.setText(list.get(position));
        holder.button.setText(list.get(position));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

}

레이아웃

더보기

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />

</androidx.constraintlayout.widget.ConstraintLayout>

recycler_view_item.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/textView"
            android:layout_width="362dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Item1"
            android:textAlignment="center" />

        <Button
            android:id="@+id/button"
            android:layout_width="212dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Item1 Button" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
반응형

'Android' 카테고리의 다른 글

Android Splash 화면 만들기  (0) 2023.04.26
전체 화면 설정  (0) 2023.04.21
RecyclerView  (0) 2023.04.16
VideoView로 동영상 재생하기  (0) 2023.04.12
Android RTSP 영상 재생하기  (0) 2023.04.11