Giới thiệu về ScrollView
ScrollView (cụ thể android.widget.ScrollView) là một FrameLayout cho phép cuộn nội dung con theo chiều dọc (vertical). Chỉ chấp nhận một view con duy nhất (thường là LinearLayout/ConstraintLayout chứa nhiều view bên trong). Không hỗ trợ cuộn ngang (dùng HorizontalScrollView cho ngang).
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project, điền thông tin cần thiết.
Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="@+id/layout"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#C1C1C1"
android:src="@drawable/a"
android:scaleType="centerCrop" />
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#C1C1C1"
android:layout_marginTop="16dp"
android:src="@drawable/b"
android:scaleType="centerCrop" />
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#C1C1C1"
android:layout_marginTop="16dp"
android:src="@drawable/c"
android:scaleType="centerCrop" />
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#C1C1C1"
android:layout_marginTop="16dp"
android:src="@drawable/d"
android:scaleType="centerCrop" />
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#C1C1C1"
android:layout_marginTop="16dp"
android:src="@drawable/e"
android:scaleType="centerCrop" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Lưu ý quan trọng:
- ScrollView chỉ có 1 child duy nhất (LinearLayout bên trong)
android:fillViewport="true"làm ScrollView mở rộng full màn hình khi nội dung ngắn- Child LinearLayout dùng
wrap_contentheight để tự co giãn theo nội dung - Cần chuẩn bị 5 drawable (a, b, c, d, e) trong res/drawable
Bước 3: Code Java - Không cần thay đổi
MainActivity.java mặc định không cần logic thêm.
Chạy ứng dụng
Kết nối thiết bị và chạy ứng dụng.

Cuộn dọc xuống:

Cuộn đến cuối:

Mẹo hay:
- NestedScrollView (Support Library) thay thế ScrollView cho tính năng lồng cuộn tốt hơn (trong CoordinatorLayout, RecyclerView...)
android:nestedScrollingEnabled="true"cho phép nested scrolling- Tránh lồng ScrollView trong ScrollView (không hoạt động đúng)
- Với danh sách dài, dùng RecyclerView thay vì ScrollView + LinearLayout (tối ưu bộ nhớ, view recycling)
scrollTo(x, y),smoothScrollTo()để cuộn lập trình