Fragment doesn't show second time it's used

旧巷老猫 提交于 2019-12-11 06:17:54

问题


I have a single Activity architecture where I'm loading a PreferenceFragmentCompat inside another ViewGroup in the MainActivity. Custom navigation exists within the MainActivity so that you can load the ViewGroup with the fragment and navigate away from it all within the same MainActivity.

The first time I navigate to the ViewGroup, the PreferenceFragmentCompat loads perfectly fine. However, when I navigate away from the ViewGroup containing the PreferenceFragmentCompat and then back again, the PreferenceFragmentCompat does not show up subsequent times. The ViewGroup does, but it's empty where the fragment should be. I can see through breakpoints/logging that the fragment is going through its lifecycle--it just isn't visible.

A new containing ViewGroup and a new PreferenceFragmentCompat object pair is created every time I navigate back to the ViewGroup, so it shouldn't be getting attached to an old ViewGroup. The navigation architecture is too complicated to post here, but here's how I'm adding the fragment in the containing ViewGroup class each time:

CustomPreferenceFragment fragment = new CustomPreferenceFragment();
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_frame_container, fragment);
ft.commit();

Does anyone have any idea why the fragment might not be showing up?


回答1:


I found the issue. It was a lot simpler than I expected. Because a new ViewGroup was being created every time, the fragment was being added to the old ViewGroup before it could be replaced by the new one, since they both contain the R.id.fragment_frame_container view. The solution was to just not create a new ViewGroup each time if it already existed.



来源:https://stackoverflow.com/questions/37039275/fragment-doesnt-show-second-time-its-used

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