滚动条,它更像一种布局,但ScrollView只能有一个孩子,只有一个孩子怎么滚动呢,所以需要先嵌套一个布局,如线性布局,这样就可以包含多个内容,内容过多就可以滚动。ScrollView只能设置垂直滚动,水平滚动有对应的HorizontalScrollView,同样它只能设置水平滚动。下面为方便测试,进重复显示相同内容。
布局XML代码
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:background="#38ff88"
android:scrollbars="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textColor="#ff0746"
android:textSize="50sp"
android:gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#0100fd"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textColor="#ff0746"
android:textSize="50sp"
android:gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#0100fd"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textColor="#ff0746"
android:textSize="50sp"
android:gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#0100fd"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textColor="#ff0746"
android:textSize="50sp"
android:gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#0100fd"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textColor="#ff0746"
android:textSize="50sp"
android:gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#0100fd"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textColor="#ff0746"
android:textSize="50sp"
android:gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#0100fd"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textColor="#ff0746"
android:textSize="50sp"
android:gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#0100fd"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textColor="#ff0746"
android:textSize="50sp"
android:gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#0100fd"/>
</LinearLayout>
</ScrollView>
效果图如下
可以看到,右边出现的灰色竖线就是滚动条显示的位置。