Search code examples
android-studiokotlinviewfragment

How to add a layout piece to a scroll view from code in kotlin


My app has two fragments and a menu at the bottom with two options to switch the views and a plus button. The first view (the second is not important (empty by now)) is containing a scrollView and I want to be able to add with the plus button some rectangle things defined in a layout file with a class they should be added one under the other. The app look The area I would like to add is highlighted in blue
The first picture shows the apps look, the second one shows the area I would like to add (it's highlighted in blue).
I don't know how to add that thing to the view neither am I atempting it correctly.


Solution

  • What you're aiming at sounds like what the RecyclerView component provides.

    It's specifically made for adding a dynamic amount of sub-views to a scrollable view "container". In other words, adding as many items to a scrollable list as you wish.

    Please do notice that RecyclerView isn't favoured by modern development standards, but then again, the entire View system has it's faults and you're not here for a lecture on Jetpack Compose... (This is a soft hint at the fact that many people dislike recycler views for their relative complexity, but they solve the specific problem you describe.)

    Please also be aware that the usage isn't exactly straightfoward if you're a beginner. It's still easier than learning a different UI framework though.

    And you already have the correct idea to define a layout for your child items that you want to add to the parent "container" layout.

    So first of all, you need to replace your scroll view with a recycler view.

    (If you're keen on sticking with your scroll view idea, then you need to add a sub LinearLayout to it. The ScrollView won't position your child elements one after another, it's not made for that. LinearLayouts are what you're looking for, in that case.)

    You also need to define the ViewHolder and the Adapter (see the example I linked above for usage). They have the job of linking views to properties and the child items to the parent list.

    While the usage might be complex at first sight (and the recycler view comes with it's own special set of issues you might encounter later on), you'll probably write just as much, if not more code, if you code your own custom solution, as you go along.