Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีใช้ RecyclerView ภายใน NestedScrollView ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตการวาง RecyclerView ภายใน NestedScrollView ซึ่งต้องการการตั้งค่าเฉพาะเพื่อให้ Scroll ทำงานถูกต้อง

ขั้นตอนที่ 1: สร้างโปรเจกต์และเพิ่ม Dependencies

ใน build.gradle (Module: app) เพิ่ม:

dependencies {
    implementation 'androidx.appcompat:appcompat:1.6.0'
    implementation 'com.google.android.material:material:1.9.0'
    implementation 'androidx.recyclerview:recyclerview:1.3.0'
    implementation 'androidx.cardview:cardview:1.0.0'
}

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (activity_main.xml)

<?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:scaleType="fitXY"
                android:src="@drawable/iphone"
                android:contentDescription="@string/app_name" />
            
            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/productList"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:scrollbars="vertical" />
                
        </LinearLayout>
    </androidx.core.widget.NestedScrollView>
</LinearLayout>

ขั้นตอนที่ 3: สร้าง Item Layout (list_item.xml)

<?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="Product Image"
            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: สร้าง Adapter Classes

ProductObject.java (Model)

package com.example.nestedscrollrecycler;

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

PhoneViewHolder.java

package com.example.nestedscrollrecycler;

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);
    }
}

PhoneAdapter.java

package com.example.nestedscrollrecycler;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class PhoneAdapter extends RecyclerView.Adapter {
    private final Context context;
    private final List productList;
    
    public PhoneAdapter(Context context, List 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 product = productList.get(position);
        int imageRes = getResourceId(context, product.getImagePath(), context.getPackageName());
        holder.phoneImage.setImageResource(imageRes);
        holder.phoneName.setText(product.getName());
    }
    
    @Override
    public int getItemCount() {
        return productList.size();
    }
    
    private static int getResourceId(Context context, String variableName, String packageName) {
        try {
            return context.getResources().getIdentifier(variableName, "drawable", packageName);
        } catch (Exception e) {
            throw new RuntimeException("Error getting Resource ID.", e);
        }
    }
}

ขั้นตอนที่ 5: เขียนโค้ดหลัก (MainActivity.java)

package com.example.nestedscrollrecycler;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
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 recyclerView = findViewById(R.id.productList);
        
        // ใช้ GridLayoutManager 2 คอลัมน์
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setHasFixedSize(true);
        
        // สำคัญ: ปิด Nested Scrolling ของ RecyclerView เพื่อให้ NestedScrollView ควบคุม Scroll
        recyclerView.setNestedScrollingEnabled(false);
        
        PhoneAdapter adapter = new PhoneAdapter(this, getProductTestData());
        recyclerView.setAdapter(adapter);
    }
    
    private List getProductTestData() {
        List list = new ArrayList<>();
        list.add(new ProductObject("iPhone 6", "iphone2"));
        list.add(new ProductObject("iPhone 6S", "iphone2"));
        list.add(new ProductObject("iPhone 8S", "iphone2"));
        list.add(new ProductObject("iPhone X", "iphone2"));
        list.add(new ProductObject("iPhone XR", "iphone2"));
        list.add(new ProductObject("iPhone XS", "iphone2"));
        return list;
    }
}

ขั้นตอนที่ 6: ตั้งค่า Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.nestedscrollrecycler">
    <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>

การทดสอบ

รันแอปพลิเคชันบนอุปกรณ์จริง Scroll ทั้งหน้าจอรวมถึง RecyclerView ได้อย่างราบรื่น

วิธีใช้ RecyclerView ภายใน NestedScrollView ใน Android

จุดสำคัญ (Key Points)

  • recyclerView.setNestedScrollingEnabled(false) - สำคัญที่สุด! ปิด scrolling ของ RecyclerView ให้ NestedScrollView จัดการ
  • android:layout_height="wrap_content" - ให้ RecyclerView ขยายตามเนื้อหา
  • android:focusableInTouchMode="true" - ช่วยให้ Scroll ทำงานได้ดีขึ้น
  • สำหรับ List แนวตั้ง ใช้ LinearLayoutManager แทน GridLayoutManager