androidandroid-fragmentsfragmentscrollview

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.


Solution

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