Android oncreateview called twice

后端 未结 1 801
时光说笑
时光说笑 2021-01-04 22:41

I have see this question asked here more than one time but I can\'t figure it out how to solve for my case.

I have an app that the user does this:

1 - Open t

相关标签:
1条回答
  • 2021-01-04 23:13

    I figure out what was my problem.

    When I was doing:

    case FRAGMENT_OPTION2:
        fragment = ControlPanelFragment.newInstance();
    break;
    

    I was creating a fragment and when I rotated the screen selectItem(int position) was again called so a new instance of the same object was created thus the steps 7 and following. The solution was to check if the fragment was already created and use him instead of creating a new one. I've saved the initial fragment with a tag and them looked for that tag. If the tag existed, use that fragment otherwise create a new one.

    public void selectItem(int position) {
            Fragment fragment = null;
            switch (position) {
                case FRAGMENT_OPTION1:
                    ...
                    break;
                case FRAGMENT_OPTION2:
                    fragment = getSupportFragmentManager().findFragmentByTag(String.valueOf(position));
                    if (fragment == null) {
                        fragment = ControlPanelFragment.newInstance();
                    }
                    break;
                ...
                case FRAGMENT_OPTIONN:
                    ...
                    return;
                default:
                    break;
            }
            if (fragment != null) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment, 
                        String.valueOf(position)).commitAllowingStateLoss();
            }
    }
    
    0 讨论(0)
提交回复
热议问题