Zach
Zach

Reputation: 10129

Add fragments to scroll view

I am trying to add fragments to a scrollview. I am dynamically creating the fragments and adding it. But its not working for me, here is my sample code

        for(int i=0; i<10;i++)
        {
            FrameLayout frame = new FrameLayout(getActivity());
            scroller.addView(frame);
            frame.setId(i+10000);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            params.leftMargin = 10;
            frame.setLayoutParams(params);

            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(i + 10000,ItemFragment.init(i));
            fragmentTransaction.commit();
            i++;
        }

But on second iteration of the loop app crashes. Whats going wrong here? Thanks.

Upvotes: 0

Views: 4541

Answers (2)

Ton Snoei
Ton Snoei

Reputation: 3195

It is possible to use a ScrollView as the host. In your situation it doesn't seem the best solution as @stkent mentioned.

If you want to use a scrollview (there can be good reasons), you have to be sure you only have one single fragment at a time within the scrollview. If not, the scrollview will crash because it contains more than one child. Therefore, don't use add() the second time and don't use replace(). Since the latest version (2022?) of the fragment manager replace() will add a new fragment first before removing the old one. This will crash the scrollview too.

Remove the old fragment first (remove()), then add the new one.

Upvotes: 0

stkent
stkent

Reputation: 20128

A ScrollView can only contain one child view. From the documentation:

A ScrollView is a FrameLayout, meaning you should place one child in it containing the entire contents to scroll; this child may itself be a layout manager with a complex hierarchy of objects.

Upvotes: 1

Related Questions