Подтвердить что ты не робот

FragmentTabHost не создает вид внутри фрагмента в android

У меня возникла проблема с отображением вида на tabhost - когда я выбираю вкладку, содержимое остается пустым.

Из того, что я могу сказать, onCreateView не вызывается на дочерних фрагментах. 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;
    }
}
4b9b3361

Ответ 1

в соответствии с документами:

Специальная вкладка TabHost, которая позволяет использовать объекты Fragment для своей вкладки содержание. При размещении этого в иерархии представлений после раздувания иерархии вы должны вызвать setup (Context, FragmentManager, int), чтобы завершите инициализацию узла вкладки.

(акцент мой)

Поэтому я предлагаю следующее:

   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;
    }
}

Ответ 2

Теперь мы можем использовать TabLayout и ViewPager делать эти вещи. Это хорошее руководство для использования. Вот мой код:

viewPager=(NonSwipeableViewPager)view.findViewById(R.id.circleresdyn_viewpager);
    tabLayout=(TabLayout)view.findViewById(R.id.circleresdyn_tablayout);

    if (viewPager != null) {
        Adapter adapter = new Adapter(((AppCompatActivity)activity).getSupportFragmentManager());
        ContentFragment con=new ContentFragment();
        con.setArguments(bundleForFramgnet);
        MemberFragment memberFragment=new MemberFragment();
        memberFragment.setArguments(bundleForFramgnet);
        CirResDynTileFragment cirResDynTileFragment=new CirResDynTileFragment();
        cirResDynTileFragment.setArguments(bundleForFramgnet);
        adapter.addFragment(cirResDynTileFragment, "Tab1");
        adapter.addFragment(con, "Tab2");
        adapter.addFragment(memberFragment, "Tab3");
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(3);
        tabLayout.setTabGravity(TabLayout.GRAVITY_CENTER);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.getTabAt(0).select();
    }

Ответ 3

Проверьте этот код. Это может помочь вам:

        import android.app.Fragment;

        public class Change_password extends Fragment {


            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
                View rootView = inflater.inflate(R.layout.change_password, container,false);
setTabs();

        return rootView;
            }



        private void setTabs() {
            try {

                addTab("Airlines", R.drawable.tab_home, HomeActivity_bkp.class);
                addTab("Advance Search", R.drawable.tab_search,
                        AdvanceSearchAcitivty.class);

                addTab("Booking", R.drawable.tab_home, Booking.class);
                addTab("Settings", R.drawable.tab_search, SettingAcitivty.class);

            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.toString(),
                        Toast.LENGTH_LONG).show();
                // TODO: handle exception
            }
        }

        private void addTab(String labelId, int drawableId, Class<?> c) {
            TabHost tabHost = getTabHost();

            Intent intent = new Intent(this, c);
            TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId);

            View tabIndicator = LayoutInflater.from(this).inflate(
                    R.layout.tab_indicator, getTabWidget(), false);
            TextView title = (TextView) tabIndicator.findViewById(R.id.title);
            title.setText(labelId);
            ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
            icon.setImageResource(drawableId);

            spec.setIndicator(tabIndicator);
            spec.setContent(intent);
            tabHost.addTab(spec);
        }