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

안드로이드 NestedScrollView에서 RecyclerView 사용하는 방법 – 단계별 예제 가이드

이 튜토리얼에서는 안드로이드 앱에서 NestedScrollView 내부에 RecyclerView를 배치하고 함께 사용하는 방법을 단계별로 살펴봅니다. 상단 이미지나 헤더 영역과 함께 스크롤되는 상품 목록 화면처럼, 여러 콘텐츠를 하나의 스크롤 흐름으로 묶어야 할 때 유용하게 활용할 수 있는 패턴입니다.

참고: NestedScrollView 안에 RecyclerView를 넣으면 뷰 재활용(View Recycling)이 일부 제한되어 항목이 많을 경우 성능이 저하될 수 있습니다. 따라서 이 방식은 헤더 + 짧은 목록 형태의 화면에 적합하며, 긴 목록에는 RecyclerView만 단독으로 사용하는 것이 좋습니다.

1단계: 프로젝트 생성 및 의존성 추가

Android Studio에서 File → New Project를 선택하여 새 프로젝트를 만들고, 필요한 정보를 모두 입력합니다.

그다음 build.gradle(Module: app) 파일에 아래 의존성을 추가합니다.

implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.intuit.sdp:sdp-android:1.0.3'

2단계: 메인 레이아웃(activity_main.xml) 작성

res/layout/activity_main.xml에 다음 코드를 추가합니다. 상단의 ImageView(상품 대표 이미지)와 RecyclerView가 NestedScrollView 안에 함께 배치되어 하나의 스크롤 영역을 이루는 구조입니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="none">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:focusableInTouchMode="true"
            android:orientation="vertical">
    <ImageView
        android:id="@+id/sellerProduct"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:adjustViewBounds="true"
        android:src="@drawable/iphone"
        android:scaleType="fitXY"
        android:contentDescription="@string/app_name" />
        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="vertical"
            android:id="@+id/productList"/>
        </LinearLayout>
    </androidx.core.widget.NestedScrollView>
</LinearLayout>

3단계: 리스트 아이템 레이아웃(list_item.xml) 작성

새 레이아웃 리소스 파일(list_item.xml)을 생성하고 아래 코드를 추가합니다. 각 상품 항목은 CardView로 감싸져 있으며, 상품 이미지와 상품명을 세로로 나열해 표시합니다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:cardElevation="2dp"
    app:cardUseCompatPadding="true">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical"
        android:padding="8dp">
        <ImageView
            android:id="@+id/phoneImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:contentDescription="TODO"
            android:src="@drawable/iphone2" />
        <TextView
            android:id="@+id/phoneName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="IPHONE"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="12sp"
            android:textStyle="bold" />
    </LinearLayout>
</androidx.cardview.widget.CardView>

4단계: 자바 클래스 파일 작성

아래 세 개의 자바 클래스 파일을 만들고, 각 파일에 해당 코드를 추가합니다.

PhoneAdapter.java

RecyclerView의 데이터 바인딩을 담당하는 어댑터 클래스입니다. 리소스 이름 문자열로부터 drawable ID를 가져오는 유틸리티 메서드도 함께 포함되어 있습니다.

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class PhoneAdapter extends RecyclerView.Adapter<PhoneViewHolder>{
    private Context context;
    private List<ProductObject> productList;
    PhoneAdapter(Context context, List<ProductObject> productList) {
        this.context = context;
        this.productList = productList;
    }
    @NonNull
    @Override
    public PhoneViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
        return new PhoneViewHolder(view);
    }
    @Override
    public void onBindViewHolder(PhoneViewHolder holder, int position){
        ProductObject productObject = productList.get(position);
        int imageRes = getResourceId(context, productObject.getImagePath(), context.getPackageName());
        holder.phoneImage.setImageResource(imageRes);
        holder.phoneName.setText(productObject.getName());
    }
    @Override
    public int getItemCount() {
        return productList.size();
    }
    private static int getResourceId(Context context, String pVariableName, String pPackageName) throws RuntimeException {
        try {
            return context.getResources().getIdentifier(pVariableName, "drawable", pPackageName);
        } catch (Exception e) {
            throw new RuntimeException("Error getting Resource ID.", e);
        }
    }
}

PhoneViewHolder.java

각 리스트 항목의 뷰(이미지, 상품명)를 보관하는 ViewHolder 클래스입니다.

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
class PhoneViewHolder extends RecyclerView.ViewHolder {
    ImageView phoneImage;
    TextView phoneName;
    PhoneViewHolder(View itemView) {
        super(itemView);
        phoneName = itemView.findViewById(R.id.phoneName);
        phoneImage = itemView.findViewById(R.id.phoneImage);
    }
}

ProductObject.java

상품 이름과 이미지 경로를 담는 데이터 모델 클래스입니다.

class ProductObject {
    private String imagePath;
    private String name;
    ProductObject(String name, String imagePath) {
        this.imagePath = imagePath;
        this.name = name;
    }
    String getImagePath() {
        return imagePath;
    }
    String getName() {
        return name;
    }
}

5단계: MainActivity.java 작성

src/MainActivity.java에 다음 코드를 추가합니다. GridLayoutManager를 사용해 상품 목록을 2열 그리드 형태로 표시하며, 테스트용 샘플 데이터를 어댑터에 전달합니다.

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView bestRecyclerView = findViewById(R.id.productList);
        GridLayoutManager mGrid = new GridLayoutManager(this, 2);
        bestRecyclerView.setLayoutManager(mGrid);
        bestRecyclerView.setHasFixedSize(true);
        PhoneAdapter mAdapter = new PhoneAdapter(MainActivity.this, getProductTestData());
        bestRecyclerView.setAdapter(mAdapter);
    }
    private List<ProductObject> getProductTestData() {
        List<ProductObject> featuredProducts = new ArrayList<>();
        featuredProducts.add(new ProductObject("Iphone 6", "iphone2"));
        featuredProducts.add(new ProductObject("Iphone 6S", "iphone2"));
        featuredProducts.add(new ProductObject("Iphone 8S", "iphone2"));
        featuredProducts.add(new ProductObject("Iphone X", "iphone2"));
        featuredProducts.add(new ProductObject("Iphone XR", "iphone2"));
        featuredProducts.add(new ProductObject("Iphone XS", "iphone2"));
        return featuredProducts;
    }
}

6단계: 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 아이콘을 클릭하세요. 실행 옵션에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같이 상단 이미지와 함께 2열 그리드로 배치된 상품 목록이 표시됩니다.

안드로이드 NestedScrollView에서 RecyclerView 사용하는 방법 – 단계별 예제 가이드