【问题标题】:Android: Is it better to create a new fragment every time a navigation drawer item is clicked, or load up previously created fragments?Android:每次单击导航抽屉项时创建一个新片段更好还是加载以前创建的片段?
【发布时间】:2013-08-23 08:28:51
【问题描述】:

我正在为 android 实现标准抽屉导航模式,用户可以从抽屉导航到大约 10 个片段。目前,每次点击不同的导航抽屉项目时,我都会创建一个新的片段,如下所示:

// When a new navigation item at index is clicked 
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
Fragment newFragment = null;
if (index == 0)
    fragment = new Fragment0();
...
ft.replace(R.id.container, newFragment);
ft.commit();

我一直想知道执行以下操作是否更有效:

// Somewhere in onCreate
Fragment[] fragments = new Fragment[n];
fragments[0] = new Fragment0();
fragments[1] = new Fragment1();
...

// When a new navigation item (at index) is clicked 
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.replace(R.id.container, fragments[index]);
ft.commit();

我主要担心的是某些片段包含大量数据(相当大的列表和大量视图)。将所有这些片段保存在内存中是否会有任何问题,并且它是否会比每次实例化新片段提供任何优势(除了片段之间的更快切换)?是否有普遍接受的“更好”解决方案?

【问题讨论】:

  • 不知findfragmentbytag能不能更有效的解决这个问题
  • 我想知道为什么android不处理片段实例化本身,比如活动。

标签: android android-fragments navigation-drawer


【解决方案1】:

我遇到了类似的问题。我采取了与您类似的方法,为了节省处理器负载,我对 every 调用进行了以下调整,以创建 Fragment 对象的实例: (在我在 selectItem 方法中使用的上下文中)

switch (position) {
    case 0:
        if (fragmentOne == null)
            fragmentOne = new FragmentOne();
        getSupportFragmentManager().beginTransaction().......
        break;
    case 1:
        if (fragmentTwo == null)
            fragmentTwo = new FragmentTwo();
        getSupportFragmentManager()......

FragmentOne 和 FragmentTwo 是两个不同的 Fragment 类,fragmentOne 和 fragmentTwo 是它们在 MainActivity 中声明为字段的对象

编辑

我想补充一下,您可以如何使用包含片段的数组遵循类似的方法。而不是在 onCreate 中创建新片段,而是在单击项目时执行此操作。在 onCreate 中,向抽屉发送调用以选择您希望在启动时默认选择的片段。

//somewhere in onCreate
if (savedInstanceState == null) {
    selectItem(defaultFragment);
}
else
    selectItem(selectedFragment);
//selectItem is method called by DrawerItemClickListener as well


//in selectItem: when navigation item at index is clicked, the listener calls this
switch (index) {
    case 0:
        if (fragments == null) {
            fragments = new Fragment[n];
            fragment[0] = new Fragment0();
        }
        else if (fragments[0] == null) {
            fragments[0] = new Fragment0();
        }
        break;
    ....
}
FragmentTransaction ft = fragmentManager.beginTransaction();
...
ft.replace(R.id.container, fragments[index]);
ft.commit();

无需在 onCreate 上实例化片段,因为这会使启动变慢。在需要时创建它们,然后使用相同的(如果存在)。仅当首次加载新片段时才会创建新片段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多