【问题标题】:How do I add scrollbars to a LinearLayout in Android?如何在 Android 中向 LinearLayout 添加滚动条?
【发布时间】:2011-08-05 09:53:06
【问题描述】:

如何在 Android 中为视图添加滚动条?

我尝试在我的布局 XML 文件中将 android:scrollbars:"vertical" 添加到 LinearLayout,但它不起作用。

我认为滚动条在 Android 中是默认绘制的,但似乎并非如此。看来我们必须自己画 - 我该怎么做?

【问题讨论】:

    标签: android scrollbar android-linearlayout


    【解决方案1】:

    您不能将滚动条添加到 LinearLayout,因为它不是可滚动容器。

    只有 ScrollViewHorizontalScrollViewListViewGridViewExpandableListView 等可滚动容器显示滚动条。

    我建议您将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上下。

    【讨论】:

    • 谢谢,你也帮了我。
    【解决方案2】:

    您不能以这种方式将滚动条添加到小部件。您可以将小部件包装在 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);
    

    【讨论】:

    • 感谢 Rajath。在我的设备上也运行良好。谢谢你这么多
    • 你可能需要强制大小:sv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    • 为什么 ScrollView layout_height 设置为 wrap_content,而不是 fill_parent
    猜你喜欢
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 2010-12-06
    • 2018-04-30
    • 1970-01-01
    • 2011-08-29
    • 2013-10-23
    • 1970-01-01
    相关资源
    最近更新 更多