如何在android中设置带有视图寻呼机的标签?

时间:2016-09-22 13:13:39

标签: android fragmentmanager

我已经按照以下instructions来获取带有视图寻呼机的滑动标签。

这是我的onCreate方法:

mViewPager.setAdapter(new NavigationPagerAdapter(getSupportFragmentManager()));
mTabLayout.setupWithViewPager(mViewPager);

这是我的导航寻呼机适配器:

public static class NavigationPagerAdapter extends FragmentPagerAdapter {
    private static final int NUM_ITEMS = 3;

    public NavigationPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    // Returns total number of pages
    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    // Returns the fragment to display for that page
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0: // Fragment # 0 - This will show FirstFragment
                return new FeedFragment();
            default:
                return null;
        }
    }

    // Returns the page title for the top indicator
    @Override
    public CharSequence getPageTitle(int position) {
        return "Page " + position;
    }
}

这是我的content_main.xml活动布局:

<android.support.design.widget.TabLayout
    android:id="@+id/navigation_sliding_tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMode="scrollable"/>

<android.support.v4.view.ViewPager
    android:id="@+id/navigation_pager"
    android:layout_width="match_parent"
    android:layout_height="0px"
    android:layout_weight="1"/>

这是我在运行代码时遇到的错误:

java.lang.NullPointerException: Attempt to write to field 'android.support.v4.app.FragmentManagerImpl android.support.v4.app.Fragment.mFragmentManager' on a null object reference

我不确定错误是否在寻呼机适配器中,但似乎片段管理器导致了问题。

1 个答案:

答案 0 :(得分:0)

在适配器中尝试此操作

FeedFragment feedfragment;
public NavigationPagerAdapter(FragmentManager fragmentManager) {
    super(fragmentManager);
    feedfragment=new FeedFragment();
}

// Returns total number of pages
@Override
public int getCount() {
    return NUM_ITEMS;
}

// Returns the fragment to display for that page
@Override
public Fragment getItem(int position) {
Fragment fragment;
    switch (position) {
        case 0: // Fragment # 0 - This will show FirstFragment
            fragment=feedfragment;
            break;
         return fragment;

    }
}

// Returns the page title for the top indicator
@Override
public CharSequence getPageTitle(int position) {
    return "Page " + position;
}
}