在TabHost更改片段未加载

时间:2014-10-14 07:18:07

标签: android android-fragments android-viewpager android-tabhost

我正在开发一个应用程序,它在FragmentActivity中使用TabHost有3个Tabs,我称之为

private void setTabContent() 
{
    mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
    mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);

    mTabHost.addTab(mTabHost.newTabSpec("trends").setIndicator("",getResources().getDrawable(R.drawable.icon_trends)),VolumeViewFragment.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("distribution").setIndicator("",getResources().getDrawable(R.drawable.icon_distribution)),ChannelsAndLanguageFilterFragment.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("Social").setIndicator("",getResources().getDrawable(R.drawable.icon_hits)),SocialDataListViewFragment.class, null);
}

现在,两个标签都有viewpager来显示像这样的片段

@Override
public void onActivityCreated(Bundle savedInstanceState) 
{
    super.onActivityCreated(savedInstanceState);
    sAdapter = new sViewPageAdapter(getFragmentManager());
    sPager = (ViewPager) getView().findViewById(R.id.social_pager);
    sPager.setBackgroundColor(color.title_background_color);
    sPager.setAdapter(sAdapter);    
}

public static class sViewPageAdapter extends FragmentPagerAdapter
{

    public sViewPageAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment f = null;
        switch(position)
        {
        case 0:
            f= SocialHitsFragment.newInstance();
            break;
            //SocialHitsFragment smFrag = new SocialHitsFragment();
            //return smFrag;
        case 1:
            f = SocialReachFragment.newInstance();
            break;
            //SocialReachFragment srFrag = new SocialReachFragment();
            //return srFrag;
        }
        return f;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return NUM_FRA;
    }

现在其中一个片段在Listview中显示数据,另一个片段显示图表。 当我第一次运行应用程序,并更改选项卡它工作正常。但当我切换回来时,片段什么都没有显示。除了显示viewpager之外,它不会加载数据。我觉得,我正在走错路或错过了什么。请帮助......我是碎片的新手..

1 个答案:

答案 0 :(得分:0)

if you are using a fragmentTabHost inside a  Fragment you can do like this,

 mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
 mTabHost.setup(this, getChildFragmentManager(), android.R.id.tabcontent);
// use getChildFragmentManager instead of getSupportFragmentManager

//检查您是否在onActiviyCreated中为ViewPager设置了页面更改侦听器    sPager.setOnPageChangeListener(本);