Android: Is it better to create a new fragment every time a navigation drawer item is clicked, or load up previously created fragments?

前端 未结 1 493
小鲜肉
小鲜肉 2021-02-01 03:18

I am implementing the standard navigation drawer pattern for android, with about 10 fragments the user can navigate to from the drawer. Currently, I am creating a new Fragment e

相关标签:
1条回答
  • 2021-02-01 04:07

    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.

    0 讨论(0)
提交回复
热议问题