片段未显示第二次使用 [英] Fragment doesn't show second time it's used
问题描述
我有一个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
加载得很好.但是,当我离开包含PreferenceFragmentCompat
的ViewGroup
并再次返回时,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屋!