如何在 Android 中使我的佈局垂直滾動?
在進入示例之前,我們應該瞭解什麼是垂直滾動檢視(滾動檢視)。垂直滾動檢視由 **android.widget.ScrollView** 類提供。它用於在垂直方向上滾動子檢視。
此示例演示如何使用垂直滾動檢視。
**步驟 1** - 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。
**步驟 2** - 將以下程式碼新增到 res/layout/activity_main.xml 中。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://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>
在以上程式碼中,我們已將線性佈局宣告為父級並添加了垂直滾動檢視。垂直滾動檢視將垂直滾動其子檢視,因此我們建立了線性佈局作為垂直滾動檢視的子級,併為線性佈局添加了子級。我們提供了五個子影像檢視進行滾動。
**步驟 3** - 無需更改 manifest.xml 和活動。
讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 移動裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟專案的一個活動檔案,然後點選工具欄中的執行圖示
。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -

以上結果是您垂直滾動時的初始螢幕,它將像下面影像所示那樣滾動 -

在以上結果中,我們正在垂直滾動 ImageView。

最終它將到達垂直滾動檢視的最後一個位置,如上所示。
點選 此處 下載專案程式碼
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP