来自另一个片段/活动后片段不显示

时间:2015-10-29 22:28:09

标签: android android-fragments android-viewpager fragmentpageradapter

我使用FragmentPagerAdapter和ViewPager来显示两个片段。第一次打开片段时,都显示/工作正常。当我去另一个活动或转到这些2之外的另一个片段然后回来时,什么都没有出现。这是代码。

事件:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Events extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.event, container, false);
    // Get the ViewPager and set it's PagerAdapter so that it can display items
    ViewPager viewPager = (ViewPager) rootView.findViewById(R.id.pager);
    FragmentManager fm = getFragmentManager();
    viewPager.setAdapter(new MyFragmentPageAdapter(fm));

    // Give the SlidingTabLayout the ViewPager
    SlidingTabLayout slidingTabLayout = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
    // Center the tabs in the layout
    slidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.ColorSecondary);
        }
    });
    slidingTabLayout.setDistributeEvenly(true);
    slidingTabLayout.setViewPager(viewPager);
    return rootView;
  }
}

MYFramentAdapter.class:

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;


public class MyFragmentPageAdapter extends FragmentPagerAdapter{

final int PAGE_COUNT = 2;
private String tabTitles[] = new String[] { "Upcoming", "Calendar" };
private Context context;

    public MyFragmentPageAdapter(FragmentManager fm) {
        super(fm);

    }
@Override
public int getCount() {
    return PAGE_COUNT;
}

@Override
public Fragment getItem(int pos) {
    switch(pos) {

        case 0: return FragmentEvents.newInstance(0);
        case 1: return  FragmentCalendar.newInstance(1);

        default: return null;
    }
}

@Override
public CharSequence getPageTitle(int position) {
    // Generate title based on item position
    return tabTitles[position];
}

}

1 个答案:

答案 0 :(得分:2)

解决:

由于嵌套片段,我不得不在ViewPager中使用getChildFragmentManager()。