ViewPager不会显示视图

时间:2015-03-01 20:07:59

标签: android android-fragments android-viewpager

我有一个ViewPager,在另一个片段中有2个片段:MainView从Fragment扩展,ViewPager的视图也从Fragment扩展。

当我运行应用程序时,一切正常,但是当我转到MainView的Fragment然后回到ViewPager的片段时 - ViewPager不会显示视图。

这是带有ViewPager代码的MainView:

    public class statistic extends Fragment {

    static final int NUM_ITEMS = 2;

    statisticViewPagerAdapter adapter;
    ViewPager viewPager;

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

        adapter = new statisticViewPagerAdapter(getFragmentManager());
        viewPager = (ViewPager) rootView.findViewById(R.id.statisticPager);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(NUM_ITEMS-1);

        return rootView;
    }
}

这是ViewPager适配器代码:

    public class statisticViewPagerAdapter extends FragmentPagerAdapter {
    static final int NUM_ITEMS = 2;

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

    @Override
    public Fragment getItem(int postion) {
        switch (postion){
            case 0: return new statisticFinance();
            case 1: return new statisticCigarettes();
            default: return null;
        }
    }

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

ViewPager XML:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}">

    <include layout="@layout/b_top_views" />
    <!-- Title -->

    <TextView
        android:id="@+id/statistic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:text="@string/statistic"
        android:textSize="16sp" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="2dp"
        android:background="#cfcfcf" />
    <!-- Pager -->
    <android.support.v4.view.ViewPager
        android:id="@+id/statisticPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"/>

</LinearLayout>

我错过了什么?如何让ViewPager显示视图?

1 个答案:

答案 0 :(得分:0)

变化:

adapter = new statisticViewPagerAdapter(getFragmentManager());

adapter = new statisticViewPagerAdapter(getChildFragmentManager());