gpt4 book ai didi

android - 在哪里调用 getChildFragmentManager()?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:12:05 27 4
gpt4 key购买 nike

问题

根据 Google 的文档:

You can now embed fragments inside fragments. This is useful for a variety of situations in which you want to place dynamic and re-usable UI components into a UI component that is itself dynamic and re-usable. For example, if you use ViewPager to create fragments that swipe left and right and consume a majority of the screen space, you can now insert fragments into each fragment page. To nest a fragment, simply call getChildFragmentManager() on the Fragment in which you want to add a fragment. This returns a FragmentManager that you can use like you normally do from the top-level activity to create fragment transactions. For example, here’s some code that adds a fragment from within an existing Fragment class:

Fragment videoFragment = new VideoPlayerFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.video_fragment, videoFragment).commit();

所以我有(例如)TestFragment,它看起来像:

public class TestFragment extends Fragment {

private View mFragmentView;
private FrameLayout mFrameLayout;

public HistoryFragment() {
super();
}

@Override
public View onCreateView(LayoutInflater pInflater, ViewGroup pViewGroup, Bundle pBundle) {

mFragmentView = pInflater.inflate(R.layout.fragment_layout, pViewGroup, false);

mFrameLayout = (FrameLayout) mFragmentView.findViewById(R.id.framelayout);

return mFragmentView;
}

public void onDestroyView() {
super.onDestroyView();
}

/* ISSUE */
public void doSomethingSpecial() {
FragmentManager tFragmentManager = getChildFragmentManager();
}
}

MainActivity 中,我像这样初始化 fragment :

mTestFragment = new TestFragment();
mTestFragment.doSomethingSpecial();

然后我通过 FragmentPagerAdapter 将 fragment 传递给 ViewPager

最后,我得到了一个异常(exception)。但如果我只使用:

mTestFragment = new TestFragment();

然后就可以了。

问题

我应该在 fragment 中的什么地方调用 getChildFragmentManager() 方法?我做错了什么?

如果您有使用新的 Android 嵌套 fragment 的好示例,请与我分享链接。非常感谢您的帮助。

最佳答案

简短回答:我在 Fragment 的 onViewCreated() 方法中调用并使用了 getChildFragmentManager()

例如:

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
addInnerFragment(); // This method does the getChildFragmentManager() stuff.
}

关于android - 在哪里调用 getChildFragmentManager()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18935505/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com