如何在 Android 中实现类似 Gallery 的 HorizontalScrollView?
在介绍示例之前,我们应该了解什么是 HorizontalScrollView。HorizontalScrollView 由 android.widget.HorizontalScrollView 类提供。它用于水平滚动子视图。
本示例演示如何使用 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>
在上面的代码中,我们将 LinearLayout 声明为父视图,并添加了一个 HorizontalScrollView。HorizontalScrollView 会水平滚动其子视图,因此我们创建了一个 LinearLayout 作为 HorizontalScrollView 的子视图,并添加了 LinearLayout 的子视图。我们为 LinearLayout 添加了五个子视图进行滚动。
步骤 3 - 无需修改 manifest.xml 和 Activity。
让我们尝试运行您的应用程序。假设您已将 Android 移动设备连接到计算机。要从 Android Studio 运行应用程序,请打开项目中的一个 Activity 文件,然后单击工具栏中的"运行"图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕。 −

以上结果是初始屏幕,当您水平滚动时,它将如下图所示滚动。

在上面的结果中,我们正在水平滚动图像视图。

最终,它将到达水平滚动视图的最后一个位置,如上图所示。

