Android, IOS/Android

[Android] RecyclerView 기본 사용법

Emil :) 2019. 12. 14. 16:02
728x90
반응형

개요


이번에 멀티메모 스와이프 삭제 기능 구현에 대해 공부하면서, 리사이클러 뷰에 대해 알게되었다.

일단 기본적인 개념은 해당 포스트에 굉장히 설명이 잘 되어있었다.

이 포스트는 아래 블로거님의 포스트를 기반으로 공부하여 나름대로 요약한 포스트이다.

https://recipes4dev.tistory.com/154?category=790402

불러오는 중입니다...

요약하자면,

기존의 리스트뷰는 데이터의 조작이나 변경이 일어나면 매번 아이템 뷰를 전체적으로 새로 구성하지만,
리사이클러 뷰는 해당 부분만 바꿔주므로, 성능 측면에서 우수하다고 볼 수 있다. 한마디로 리스트뷰의 업그레이드버전.

그렇다면 리사이클러 뷰를 한번 만들어보자.

 

구성 요소


우리는 리스트뷰의 아이템 하나 하나를 원하는 모양으로 커스터마이징 하려면, 어댑터를 만들어주고, 어댑터의 getView에서 커스터마이징 해줬다.

리사이클러뷰도 마찬가지로 어댑터를 사용하고, getView 역할을 하는 것이 LayoutManager라는 것을 통해 이루어진다.

이미지 출처 - https://recipes4dev.tistory.com/154

리사이클러뷰는 크게
리사이클러뷰, 어댑터, 레이아웃 매니저, 뷰 홀더로 나눌 수 있다 뷰 홀더는 화면에 표시될 아이템 뷰를 저장하는 객체다.

 

실습해보기


먼저 간단한 xml파일을 만들어주자, 메인 화면이다. 기존에 쓰던 멀티메모를 확장하고자 미리 임의의 버튼을 하나 나눠봤다.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="10">
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler1"
            android:scrollbars="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>

</LinearLayout>

다음은 아이템을 표시할 뷰 레이아웃이다. 참고한 블로그는 텍스트 뷰만 사용했지만, 카드뷰로 이미지까지 넣어봤다.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardElevation="5dp"
    app:cardCornerRadius="5dp"
    android:layout_marginBottom="1dp"
    android:layout_marginLeft="2dp"
    android:layout_marginRight="2dp"
    android:layout_marginStart="2dp"
    android:layout_marginEnd="2dp"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        >

        <ImageView
            android:id="@+id/iv_picture"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center_vertical"
            android:layout_margin="10dp"
            tools:src="@drawable/bread"
            />

        <TextView
            android:id="@+id/tv_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:textSize="20sp"
            tools:text="5,000원"
            />

    </LinearLayout>

</android.support.v7.widget.CardView>

그다음 리사이클러뷰 어댑터를 구현한다. 여기서 리스트뷰와 다른점이 있는데, 리스트뷰는 기본제공되는 어댑터를 사용하거나 baseAdapter를 상속받아 사용했지만,
리사이클러뷰는 반드시 개발자가 어댑터를 직접 구현해야한다.

그리고 이 때, RecyclerView.Adapter를 상속받아 새로운 어댑터를 만든다. 재정의(Override)가 필요한 메서드는 다음과 같다.

이미지 출처 - https://recipes4dev.tistory.com/154

이 과정에선 다른 블로그를 참조했다. 이 포스팅이 내가 배운것과 코드가 유사해서 이해하기가 쉬웠다.

https://dreamaz.tistory.com/345

 

안드로이드 RecyclerView(리싸이클러뷰) 사용법 가이드

안녕하세요. 개발자 드리머즈입니다. 이번 포스트에선 간단한 안드로이드 RecyclerView를 만들어 보겠습니다. 위 사진과 같은 RecyclerView를 만드는 것이 목표입니다. RecyclerView 내부의 Row(행)을 좀 더 예쁘..

dreamaz.tistory.com

 

이 블로그의 내용을 보면서 따라해봤다.

먼저 리사이클러뷰를 사용하려면 다음과 같이 gradle에 추가해줘야된다.

dependencies {
   
    implementation 'com.android.support:cardview-v7:28.1.0'
    implementation 'com.android.support:recyclerview-v7:28.1.0'
}

자신의 버전에 맞게 바꿔주자. 참고로 이 과정에서 androidx와의 호환도 문제가 많이발생한다..
안드로이드는 진짜 너무 빨리바뀌는것 같다..

다음은 음식 정보를 가진 자바 파일을 만들어주자.

FoodInfo.java

package com.example.a2_recyclerview;

public class FoodInfo {
    public int drawableId;
    public String price;

    public FoodInfo(int drawableId, String price){
        this.drawableId = drawableId;
        this.price = price;
    }
}

 그리고 MainActivity.java를 짜준다.

package com.example.a2_recyclerview;

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

import android.os.Bundle;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    RecyclerView mRecyclerView;
    RecyclerView.LayoutManager mLayoutManager;

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

        //리사이클러 뷰 객체 생성 및 연결
        mRecyclerView = findViewById(R.id.recycler1);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);

        //음식 정보에 .add써서 넣어주기
        ArrayList<FoodInfo> foodInfoArrayList = new ArrayList<>();
        foodInfoArrayList.add(new FoodInfo(R.drawable.bread, "4,600원"));
        foodInfoArrayList.add(new FoodInfo(R.drawable.noodle, "4,200원"));
        foodInfoArrayList.add(new FoodInfo(R.drawable.strawberry, "5,000원"));

        //내 어댑터에 이 동적리스트를 인자로 넘겨주기
        MyAdapter myAdapter = new MyAdapter(foodInfoArrayList);

        //어댑터 설정하기
        mRecyclerView.setAdapter(myAdapter);
    }
}

 결과는 이렇게 나온다

이제 리사이클러 뷰가 어떻게 작동하는지 알았다, 스와이프 메뉴를 구상해보자..!!!

728x90
반응형