Home > other >  ScrollView does not work when adding TextViews programmatically
ScrollView does not work when adding TextViews programmatically

Time:01-05

I have a ScrollView and a LinearLayout within it defined in the xml file.

    <ScrollView
        android:id="@ id/planList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="8dp"
        android:paddingTop="8dp"
        android:paddingRight="8dp"
        android:paddingBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/button"
        app:layout_constraintVertical_bias="0.0">

        <LinearLayout
            android:id="@ id/planListView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>

I add TextViews programmatically from the Activity.

    val textView = TextView(this)
    textView.text = text
    textView.setPadding(0, 8, 0, 8)
    textView.breakStrategy = LineBreaker.BREAK_STRATEGY_BALANCED
    binding.planListView.addView(textView)

It fills up the linearLayout. When the list exceeds the available size the scrollbar does not appear and no scrolling available at all.

What is wrong? How can I make it work?

Thank you in advance.

CodePudding user response:

To make it works you need set layout properties properly.

texView.setLayoutParams(new LinearLayout.LayoutParams(
        LayoutParams.FILL_PARENT,
        LayoutParams.WRAP_CONTENT));

binding.planListView.addView(textView)

CodePudding user response:

ScrollViews scroll when their contents are larger than the ScrollView itself - it acts as a window, allowing you to move the contents back and forth so you can see different parts. If you set the height to wrap_content, you're ensuring the ScrollView will always be the same height as its contents - so it won't scroll, and it will potentially be partially off the screen (which is what's happening here - you can use the Layout Inspector to check, you'll see the view extending below the screen area).

You need to either give the ScrollView a fixed height, or otherwise constrain it so it won't extend off the screen when its contents grow too large. Generally, there'll be an area in your UI where you want the scrollable content window to appear - that area is your ScrollView. If its contents are too big to fit inside that area, it'll allow scrolling. That's about it!

  • Related