android - FragmentTabHost 没有在 android 的 Fragment 内创建 View

标签 android android-fragments android-tabhost fragment-tab-host android-nested-fragment

我在更改选项卡主机上的 View 时遇到问题 - 当我选择一个选项卡时,内容保持空白。

据我所知,onCreateView 并未在子 fragment 上调用onMenuCreate 运行良好,因为菜单会按预期更改。

   public class PatientTabFragment extends Fragment {
    private FragmentTabHost mTabHost;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mTabHost = new FragmentTabHost(getActivity());
        mTabHost.setup(getActivity(), getChildFragmentManager());

        mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Info"),
                NewPatientFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Notes"),
                NoteListFragment.class, null);


        return mTabHost;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mTabHost = null;
    }
}

最佳答案

根据 the docs :

Special TabHost that allows the use of Fragment objects for its tab content. When placing this in a view hierarchy, after inflating the hierarchy you must call setup(Context, FragmentManager, int) to complete the initialization of the tab host.

(强调我的)

所以我建议这样:

   public class PatientTabFragment extends Fragment {
    private FragmentTabHost mTabHost;
    private boolean createdTab = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mTabHost = new FragmentTabHost(getActivity());
        mTabHost.setup(getActivity(), getChildFragmentManager());

        mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Info"),
                NewPatientFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Notes"),
                NoteListFragment.class, null);


        return mTabHost;
    }

    public void onResume(){
        if (!createdTab){
          createdTab = true;
          mTabHost.setup(getActivity(), getActivity().
                         getSupportedFragmentManager());
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mTabHost = null;
    }
}

关于android - FragmentTabHost 没有在 android 的 Fragment 内创建 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21064298/

相关文章:

android - 共享意向位置

android - 如何同时使用抽屉导航和底部导航 - 导航架构组件

android - 如何在不改变按钮大小的情况下改变按钮的颜色?

java - Android - 将数据从父 fragment 传递到子 fragment

android - 使用 BroadCast Receiver 与 Listener 与当前显示的 Fragment 通信

android - 当我升级 android.support.v4 时 Tabhost 内容不显示

android - flutter - 使用抽屉子部件 onTap 更改子部件

Android全屏对话框回调问题

java - Scrollview 中的 TabHost 在内容更改时滚动

android - 在哪里可以找到 Android 选项卡图标