When inflating fragment which was previously inflated app crashes

后端 未结 1 872
醉话见心
醉话见心 2021-01-06 11:11

The app loads and views EventFragment.java which displays a map. When you click another tab fragment it loads that in fine, when you go back to the first tab (t

1条回答
  •  孤街浪徒
    2021-01-06 12:05

    I've been fighting with this same issue all day today. I got mine working earlier. Here's what I did: When changing the fragment showing, I first remove the old mapFragment, then do what I normally do when adding new fragments.

    Fragment oldMapFrag = getSupportFragmentManager().findFragmentById(R.id.map);
    if(oldMapFrag != null) {
        getSupportFragmentManager().beginTransaction().remove(oldMapFrag).commit();
        manager.popBackStack();
        ViewGroup container = (ViewGroup)findViewById(R.id.content);
        if(container != null)
            container.removeAllViews();
    }
    

    When I want to view the mapFragment again, I remove the previous fragment then inflate the view with the mapFragment again:

    Fragment currentFrag = getSupportFragmentManager().findFragmentById(R.id.content);
    if(currentFrag != null) {
        getSupportFragmentManager().beginTransaction().remove(currentFrag).commit();
        manager.popBackStack();
    }
    View mapView = inflator.inflate(R.layout.store_finder, container, true);
    

    I don't know why getSupportFragmentManager().beginTransaction().remove(oldMapFrag).commit(); works in the first step because you shouldn't be able to remove fragments defined in XML, but this does work for me. I hope it helps.

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