【发布时间】:2011-08-05 09:53:06
【问题描述】:
如何在 Android 中为视图添加滚动条?
我尝试在我的布局 XML 文件中将 android:scrollbars:"vertical" 添加到 LinearLayout,但它不起作用。
我认为滚动条在 Android 中是默认绘制的,但似乎并非如此。看来我们必须自己画 - 我该怎么做?
【问题讨论】:
标签: android scrollbar android-linearlayout
如何在 Android 中为视图添加滚动条?
我尝试在我的布局 XML 文件中将 android:scrollbars:"vertical" 添加到 LinearLayout,但它不起作用。
我认为滚动条在 Android 中是默认绘制的,但似乎并非如此。看来我们必须自己画 - 我该怎么做?
【问题讨论】:
标签: android scrollbar android-linearlayout
您不能将滚动条添加到 LinearLayout,因为它不是可滚动容器。
只有 ScrollView、HorizontalScrollView、ListView、GridView、ExpandableListView 等可滚动容器显示滚动条。
我建议您将LinearLayout 放在ScrollView 中,如果有足够的内容可以滚动,默认情况下会显示垂直滚动条。
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<!-- Your content goes here -->
</LinearLayout>
</ScrollView>
如果您希望始终显示垂直滚动条,请将android:scrollbarAlwaysDrawVerticalTrack="true" 添加到您的ScrollView。注意LinearLayout 的高度设置为wrap_content - 这意味着如果有足够的内容,LinearLayout 的高度可以大于ScrollView 的高度 - 在这种情况下,您将能够滚动您的LinearLayout上下。
【讨论】:
您不能以这种方式将滚动条添加到小部件。您可以将小部件包装在 ScrollView 中。这是一个简单的例子:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/txt"/>
</LinearLayout>
</ScrollView>
如果你想用代码来做:
ScrollView sv = new ScrollView(this);
//Add your widget as a child of the ScrollView.
sv.addView(wView);
【讨论】:
layout_height 设置为 wrap_content,而不是 fill_parent?