Trước khi đi vào ví dụ, chúng ta nên biết Vertical Scroll View (ScrollView) là gì. Vertical Scroll View được cung cấp bởi lớp android.widget.ScrollView. Nó được dùng để cuộn các view con theo chiều dọc.
Ví dụ này minh họa cách sử dụng Vertical Scroll View.
Bước 1
Tạo một dự án mới trong Android Studio, vào File → New Project và điền đầy đủ thông tin cần thiết để tạo dự án mới.
Bước 2
Thêm mã sau vào 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"> <LinearLayout android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent"> <ImageView android:layout_width="match_parent" android:background="#c1c1c1" android:layout_height="300dp" android:src="@drawable/a"/> <ImageView android:layout_width="match_parent" android:background="#c1c1c1" android:layout_height="300dp" android:layout_marginTop="30dp" android:src="@drawable/b"/> <ImageView android:layout_width="match_parent" android:background="#c1c1c1" android:layout_height="300dp" android:layout_marginTop="30dp" android:src="@drawable/c"/> <ImageView android:layout_width="match_parent" android:background="#c1c1c1" android:layout_height="300dp" android:layout_marginTop="30dp" android:src="@drawable/d"/> <ImageView android:layout_width="match_parent" android:background="#c1c1c1" android:layout_height="300dp" android:layout_marginTop="30dp" android:src="@drawable/e"/> </LinearLayout> </ScrollView> </LinearLayout>
Trong mã trên, chúng ta khai báo LinearLayout làm cha và thêm Vertical ScrollView. Vertical ScrollView sẽ cuộn view con theo chiều dọc nên chúng ta tạo LinearLayout làm con cho Vertical ScrollView và thêm các view con cho LinearLayout. Chúng ta cho 5 ImageView con để cuộn.
Bước 3
Không cần thay đổi manifest.xml và activities.
Hãy thử chạy ứng dụng. Giả sử bạn đã kết nối thiết bị Android thực tế với máy tính. Để chạy ứng dụng từ Android Studio, mở một file activity của dự án và nhấn biểu tượng Run
từ thanh công cụ. Chọn thiết bị di động của bạn làm tùy chọn và kiểm tra thiết bị sẽ hiển thị màn hình mặc định:

Kết quả trên là màn hình ban đầu. Khi cuộn dọc nó sẽ cuộn như hình dưới:

Trong kết quả trên, chúng ta đang cuộn các ImageView theo chiều dọc.

Cuối cùng nó sẽ đến vị trí cuối của Vertical ScrollView như hình trên.