【问题标题】:Why use serialization to pass info to a fragment?为什么使用序列化将信息传递给片段?
【发布时间】:2015-03-30 11:13:40
【问题描述】:

我有一个类似片段的列表,目前我正在传递这样的信息:

片段:

public void populate(Map<String, List<Book>> booksGroupedByType)
{
    BookListAdapter bookListAdapter = new BookListAdapter(this.getActivity(), booksGroupedByType);
    _lstBooks.setAdapter(bookListAdapter);
}

活动:

private void populateBooksFragment()
{
    Map<String, List<Book>> booksGroupedByType = _repository.getAllBooksGroupedByType();
    BookListFragment bookListFragment = (BookListFragment) getFragment(R.id.fragBooks);
    if (bookListFragment != null)
    {
        bookListFragment.populate(booksGroupedByType);
    }
}

然后我觉得如果我可以在创建片段时传递这些信息会更好,因为我们没有可用的构造函数我查找了该方法并发现了这个:

public static DetailsFragment newInstance(int index) {
    DetailsFragment f = new DetailsFragment();
    // Supply index input as an argument.
    Bundle args = new Bundle();
    args.putInt("index", index);
    f.setArguments(args);
    return f;
}

我尝试实现,但发现我的 Map 无法序列化,需要更多工作。所以我的问题是,为什么要经历这个?使用我的原始方法(填充)是否有缺点,甚至比序列化更快?

我想也许我的片段在旋转时会丢失其数据,但不会,在旋转时(在模拟器中)列表保持不变。

【问题讨论】:

  • 这很好地回答了你的问题stackoverflow.com/questions/10450348/…
  • @Rohit5k2 我根本没有使用构造函数,所以恢复状态是唯一剩下的问题吗?我做了设备旋转,但这并没有搞砸任何事情......

标签: android android-activity android-fragments serialization


【解决方案1】:

假设您有一些以时间/资源消耗方式获得的数据。如果您不想在每次配置更改(并且活动被破坏)时下载它们,则必须以某种方式持久化它们。

第一个选项是将数据放入包中,因此即使在系统自动重新创建片段后,它也可用于片段。它可能适用于简单类型,但对于任意对象,由于性能原因(序列化/打包),它通常不是一个选项。

第二个选项是保留片段,方法是在片段的 onCreate() 中设置一个标志:

setRetainInstanceState(true)

在这种情况下,配置更改后片段不会被销毁,而只是从被销毁的活动中分离出来,并附加到新的活动中。您将传递的任何数据,例如via setter 也将可用。

另请参阅:Understanding Fragment's setRetainInstance(boolean)

【讨论】:

    猜你喜欢
    • 2014-09-21
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多