如何在Android中實現類似Gallery的HorizontalScrollView?
在進入示例之前,我們應該瞭解什麼是HorizontalScrollView。HorizontalScrollView 由 **android.widget.HorizontalScrollView** 類提供。它用於水平方向滾動子檢視。
此示例演示如何使用水平滾動檢視。
步驟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"> <HorizontalScrollView android:layout_width="match_parent" android:layout_height="300dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="300dp" android:background="#c1c1c1" android:layout_height="match_parent" android:src="@drawable/a"/> <ImageView android:layout_width="300dp" android:background="#c1c1c1" android:layout_height="match_parent" android:layout_marginLeft="30dp" android:src="@drawable/b"/> <ImageView android:layout_width="300dp" android:background="#c1c1c1" android:layout_height="match_parent" android:layout_marginLeft="30dp" android:src="@drawable/c"/> <ImageView android:layout_width="300dp" android:background="#c1c1c1" android:layout_height="match_parent" android:layout_marginLeft="30dp" android:src="@drawable/d"/> <ImageView android:layout_width="300dp" android:background="#c1c1c1" android:layout_height="match_parent" android:layout_marginLeft="30dp" android:src="@drawable/e"/> </LinearLayout> </HorizontalScrollView> </LinearLayout>
在上面的程式碼中,我們宣告線性佈局作為父佈局,並添加了 HorizontalScrollView。HorizontalScrollView 將水平滾動其子檢視,因此我們建立了一個線性佈局作為 HorizontalScrollView 的子項,併為線性佈局添加了子項。我們添加了五個子影像檢視進行滾動。
步驟3 − 無需更改 manifest.xml 和活動。
讓我們嘗試執行您的應用程式。我假設您已將實際的 Android 移動裝置連線到您的計算機。要在 Android Studio 中執行應用程式,請開啟專案的某個活動檔案,然後單擊工具欄中的執行圖示 。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 −
上述結果是初始螢幕,當您水平滾動時,它將像下面的影像一樣滾動 −
在上面的結果中,我們正在水平滾動影像檢視。
最終它將到達水平滾動檢視的最後一個位置,如上所示。
點選 此處 下載專案程式碼
廣告