开发者

How do I add scrollbars to a LinearLayout in Android?

开发者 https://www.devze.com 2023-02-24 08:51 出处:网络
How do I add scrollbars to a view in Android?开发者_如何转开发 I tried by adding android:scrollbars:\"vertical\" to the LinearLayout in my layout XML filebut it is not working.

How do I add scrollbars to a view in Android?开发者_如何转开发

I tried by adding android:scrollbars:"vertical" to the LinearLayout in my layout XML file but it is not working.

I thought scrollbars were drawn by default in Android but it does not seem that way. It seems we have to draw it ourselves - how do I do this?


You cannot add scrollbars to a LinearLayout because it is not a scrollable container.

Only scrollable containers such as ScrollView, HorizontalScrollView, ListView, GridView, ExpandableListView show scrollbars.

I suggest you place your LinearLayout inside a ScrollView which will by default show vertical scrollbars if there is enough content to scroll.

<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>

If you want the vertical scrollbar to always be shown, then add android:scrollbarAlwaysDrawVerticalTrack="true" to your ScrollView. Note the height of the LinearLayout is set to wrap_content - this means the height of the LinearLayout can be larger than that of the ScrollView if there is enough content - in that case you will be able to scroll your LinearLayout up and down.


You can't add a scrollbar to a widget that way. You can wrap your widget inside a ScrollView. Here's a simple example:

<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>

If you want to do it in code:

ScrollView sv = new ScrollView(this);
//Add your widget as a child of the ScrollView.
sv.addView(wView);
0

精彩评论

暂无评论...
验证码 换一张
取 消