Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 823
mollymay Avatar asked Jun 23 '13 14:06

mollymay


1 Answers

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.
like image 154
einschnaehkeee Avatar answered Oct 27 '22 14:10

einschnaehkeee