【Android】NestedScrollView内にRecyclerViewを実装する方法を徹底解説
このチュートリアルでは、AndroidアプリにおいてNestedScrollViewの中に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'
なお、近年のAndroid Studioでは新規プロジェクトでAndroidXがデフォルトで有効になるため、既存プロジェクトへ組み込む場合はサポートライブラリではなくAndroidX系ライブラリの利用を推奨します。
ステップ2:activity_main.xmlの作成
res/layout/activity_main.xmlに以下のコードを記述します。NestedScrollViewの直下にLinearLayoutを配置し、その中にヘッダー用のImageViewとRecyclerViewを縦方向に並べる構成です。
<?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:id="@+id/productList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</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:Javaクラスの作成
以下の3つのJavaクラスを作成し、それぞれ対応するコードを記述していきます。
PhoneAdapter.java
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);
}
}
}
このアダプターは、リストの各位置に対応する商品データを取得し、drawableリソースIDを動的に解決したうえで、画像と製品名を各アイテムにバインドします。
PhoneViewHolder.java
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;
}
}
ProductObjectは、製品名と画像リソース名を保持するシンプルなデータクラス(モデル)です。
ステップ5:MainActivity.javaの実装
src/MainActivity.javaに以下のコードを追加します。GridLayoutManagerを使ってRecyclerViewを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端末をPCに接続していることを前提に説明します。Android Studioでプロジェクト内のいずれかのアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。接続したモバイル端末を選択すると、端末上にアプリの初期画面が表示され、NestedScrollView内にRecyclerViewによる商品リストが正しく描画されていることが確認できます。

補足:NestedScrollView+RecyclerView利用時の注意点
NestedScrollViewの中にRecyclerViewを直接配置した場合、RecyclerView本来の「ビューの再利用(リサイクル)」が効きにくくなります。そのため、アイテム数が多いリストではメモリ使用量の増加やスクロールのカクつきが発生する可能性があります。
対策として、以下のようにsetNestedScrollingEnabled(false)を呼び出すと、スクロールイベントがNestedScrollView側に委譲され、より自然で滑らかなスクロール体験を実現できます。
bestRecyclerView.setNestedScrollingEnabled(false);
また、単に「ヘッダー+リスト」という画面構成を実現したいだけであれば、RecyclerViewの複数ビュータイプやConcatAdapterを活用する方法も検討する価値があります。用途に応じて最適な実装を選びましょう。
-
【Android】データベースとRecyclerViewを連携させる方法を実装例つきで解説
この記事では、AndroidアプリでRecyclerViewとデータベース(SQLite)を連携させて使用する方法を、実際のサンプルコードとともに解説します。連絡先の登録・表示・編集・削除ができるシンプルなアプリを題材に、実装手順をステップごとに見ていきましょう。ステップ1:プロジェクトの作成と依存関係の追加まず、Android Studioで新しいプロジェクトを作成します。メニューから「File → New Project」を選択し、必要事項を入力してプロジェクトを作成してください。続いて、build.gradle(Module: app)に以下の依存関係を追加します。implementat
-
【Android】NavigationViewの実装方法をステップごとに解説
この記事では、AndroidアプリでNavigationView(ナビゲーションビュー)を使用してドロワーメニューを実装する方法を、ステップごとに詳しく解説します。ハンバーガーアイコンから開閉できるサイドメニューは、多くのアプリで採用されている定番のUIです。ステップ1:新しいプロジェクトを作成するAndroid Studioを開き、File → New Project を選択して、必要な情報を入力し新しいプロジェクトを作成します。テンプレートには「Navigation Drawer Activity」を選ぶと、後の作業がスムーズになります。ステップ2:activity_main.xml にコ