31

我正在为 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();

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

4

1 回答 1

6

I had a similar issue. I took an approach similar to yours, and to save load on processor I made the following tweak to every call to create an instance for a Fragment object: (in context to my use in selectItem method)

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

FragmentOne and FragmentTwo are the two different Fragment classes and fragmentOne and fragmentTwo are their objects declared as fields in MainActivity

Edit:

I would like to add how you could follow a similar approach with the array holding the fragments. Instead of creating new fragments in onCreate, do that when an item is clicked. In onCreate, send a call to the drawer to select the fragment which you want selected by default on launch.

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

No need to instantiate the fragments on onCreate since that makes the startup slow. Create them as and when needed and afterwards use the same one if it exists. The new fragments are created only if they are being loaded for the first time.

于 2013-10-17T20:25:48.360 回答