如何在Android中向LinearLayout添加滚动条?

Ang*_*gel 18 android scrollbar android-linearlayout

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

我尝试添加android:scrollbars:"vertical"LinearLayout我的布局XML文件但它无法正常工作.

我认为默认情况下在Android中绘制了滚动条,但它似乎并非如此.看来我们必须自己画画 - 我该怎么做?

Jos*_*arl 50

您无法将滚动条添加到a,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>
Run Code Online (Sandbox Code Playgroud)

如果您希望始终显示垂直滚动条,请添加android:scrollbarAlwaysDrawVerticalTrack="true"到您的ScrollView.请注意,高度LinearLayout设置为wrap_content- 这意味着高度LinearLayout可以大于ScrollView有足够内容的高度- 在这种情况下,您可以LinearLayout向上和向下滚动.


raj*_*ath 11

您无法以这种方式向窗口小部件添加滚动条.你可以将你的小部件包装在一个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>
Run Code Online (Sandbox Code Playgroud)

如果你想在代码中这样做:

ScrollView sv = new ScrollView(this);
//Add your widget as a child of the ScrollView.
sv.addView(wView);
Run Code Online (Sandbox Code Playgroud)