6

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)

4

1 回答 1

1

如果要添加的 Fragment 数量不定,最好使用带有 FragmentStatePagerAdapter 或 FragmentPagerAdapter 的 ViewPager。在那里,您可以以干净的方式添加无限数量的片段,而不必担心使用大量内存的大量片段列表。

如果您想继续使用 ScrollView 方法,可以使用 FragmentManager.executePendingTransactions() 来确保事务在另一个之前完成:

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.
于 2014-05-14T14:19:07.620 回答