【问题标题】:Multiple fragments in a vertical Linearlayout垂直线性布局中的多个片段
【发布时间】:2013-06-20 03:25:36
【问题描述】:

我在我的应用程序中遇到以下问题。我想以特定顺序将多个片段添加到垂直 LinearLayout 中。

这是我的布局

<?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>

这是我用来添加片段的代码。

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();

我每次都使用一笔交易,因此我保证它们在屏幕上按该顺序放置。

我的问题是,当方向改变并重新创建 Activity 时,我无法确定它们会以相同的顺序出现在屏幕上。

有人也经历过吗?我该如何解决这个问题?在 LinearLayout 中有两个布局,每个片段都有一个特定的 id 将无济于事,因为我必须添加的片段数量是不确定的(我只是在示例中使用了数字 2)

【问题讨论】:

  • 也许setRetainInstance 对你有用
  • 你有没有机会解决这个问题?我一直在寻找一段时间没有找到答案。我只需要在运行时动态地将 X 个(可以变化的)片段添加到线性布局中。

标签: android layout fragment


【解决方案1】:

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

如果您想继续使用 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.

【讨论】:

    猜你喜欢
    • 2015-07-27
    • 1970-01-01
    • 2017-08-26
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多