mollymay
mollymay

Reputation: 512

Multiple fragments in a vertical Linearlayout

I am facing the following issue in my app. I want to add multiple fragments into a vertical LinearLayout in a certain order.

Here is my layout

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/scrollview"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:fillViewport="true" >
<LinearLayout 
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
</LinearLayout>
</ScrollView>

And here is the code I use to add the fragments.

Fragment fragment1 = MyFragment.newInstance(param1);
Fragment fragment2 = MyFragment.newInstance(param2);

FragmentManager fm = getSupportFragmentmanager();

fm.beginTransaction().add(R.id.content, fragment1, "fragment1").commit();
fm.beginTransaction().add(R.id.content, fragment2, "fragment2").commit();

I use one transaction each time so I guarantee that they are placed in that order on screen.

My problem is that when the orientation changes and the Activity is re-created there is no way I can be sure that they will appear on screen in the same order.

Has someone experienced this too? How can I solve the problem? Having two layouts inside the LinearLayout with an specific id for each of the fragments will not help, because the number of fragments I have to add is undetermined (I just used the number 2 for the example)

Upvotes: 6

Views: 1876

Answers (1)

einschnaehkeee
einschnaehkeee

Reputation: 1888

If there's an indefinite amount of Fragments to add, better use a ViewPager with a FragmentStatePagerAdapter or FragmentPagerAdapter. There you can add inifinite numbers of Fragments in a clean way and don't have to worry about a huge list of Fragments using a large amount of memory.

If you want to stay with your ScrollView approach, you can use FragmentManager.executePendingTransactions() to ensure, that the transaction is completed, before the other:

FragmentManager fm = getSupportFragmentmanager();

fm.beginTransaction().add(R.id.content, fragment1, "fragment1").commit();
fm.executePendingTransactions();
fm.beginTransaction().add(R.id.content, fragment2, "fragment2").commit();
fm.executePendingTransactions();
// etc.

Upvotes: 1

Related Questions