如何使我的佈局垂直滾動?


在進入示例之前,我們應該瞭解什麼是垂直滾動檢視(滾動檢視)。垂直滾動檢視由 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>

在上面的程式碼中,我們宣告線性佈局為父佈局,並添加了垂直滾動檢視。垂直滾動檢視將垂直滾動其子檢視,因此我們建立了線性佈局作為垂直滾動檢視的子項,併為線性佈局添加了子項。我們提供了五個子影像檢視進行滾動。

步驟 - 無需更改 manifest.xml 和活動。

讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 移動裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟您專案中的一個活動檔案,然後單擊執行  工具欄中的圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -

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

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

最後,它將到達垂直滾動檢視的最後一個位置,如上所示。

點選 這裡 下載專案程式碼

更新於:2019年7月30日

246 次瀏覽

啟動您的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.