片段未显示第二次使用 [英] Fragment doesn't show second time it's used

查看:315
本文介绍了片段未显示第二次使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Activity架构,在其中将PreferenceFragmentCompat加载到MainActivity中的另一个ViewGroup中. MainActivity中存在自定义导航,因此您可以在片段中加载ViewGroup,并在同一MainActivity中将其全部导航.

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.

我第一次导航到ViewGroup时,PreferenceFragmentCompat加载得很好.但是,当我离开包含PreferenceFragmentCompatViewGroup并再次返回时,PreferenceFragmentCompat不会在以后出现. ViewGroup可以,但是片段应该在的位置为空.通过断点/记录,我可以看到该片段正在经历其生命周期-只是不可见.

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.

每次导航回ViewGroup时,都会创建一个包含ViewGroup和新的PreferenceFragmentCompat对象对的新对象,因此不应将其附加到旧的ViewGroup上.导航架构太复杂了,无法在此处发布,但这是我每次在包含ViewGroup类的片段中添加片段的方式:

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?

推荐答案

我发现了问题.这比我预期的要简单得多.由于每次都创建一个新的ViewGroup,因此该片段已被添加到旧的ViewGroup中,然后才能被新的ViewGroup替换,因为它们都包含R.id.fragment_frame_container视图.解决方案是仅在每次已有的ViewGroup不存在时都创建一个新的.

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.

这篇关于片段未显示第二次使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆