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

℡╲_俬逩灬. 提交于 2019-12-02 18:02:22

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!