标签不显示(ViewPager)

时间:2017-12-22 17:25:44

标签: java android

我有一个问题,就是没有选择标签 它没有给我任何错误,但它不起作用 我不知道我做错了什么 我希望拥有与本教程enter link description here

相同的功能

这是MainActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mViewPager = (ViewPager) findViewById(R.id.main_tabPager);
    setupViewPager(mViewPager);

    mTabLayout = (TabLayout) findViewById(R.id.main_tabs);
    mTabLayout.setupWithViewPager(mViewPager);
}
private void setupViewPager(ViewPager viewPager){
    SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new FavouriteFragment(), "Favourite");
    adapter.addFragment(new MostPopularFragment(), "The most popular");
    adapter.addFragment(new NewestFragment(), "The newest");
    viewPager.setAdapter(adapter);
}

这是SectionsPagerAdapter:

private final List<Fragment> M_FRAGMENT_LIST = new ArrayList<>();
private final List<String> M_FRAGMENT_TITLE = new ArrayList<>();

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

public void addFragment(Fragment fragment, String title){
    M_FRAGMENT_LIST.add(fragment);
    M_FRAGMENT_TITLE.add(title);
}

@Override
public Fragment getItem(int position) {
    return M_FRAGMENT_LIST.get(position);
}

@Override
public CharSequence getPageTitle(int position) {
    return M_FRAGMENT_TITLE.get(position);
}

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

1 个答案:

答案 0 :(得分:2)

您要将getCount()归还为零

    private final List<Fragment> M_FRAGMENT_LIST = new ArrayList<>();
private final List<String> M_FRAGMENT_TITLE = new ArrayList<>();

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

public void addFragment(Fragment fragment, String title){
    M_FRAGMENT_LIST.add(fragment);
    M_FRAGMENT_TITLE.add(title);
}

@Override
public Fragment getItem(int position) {
    return M_FRAGMENT_LIST.get(position);
}

@Override
public CharSequence getPageTitle(int position) {
    return M_FRAGMENT_TITLE.get(position);
}

@Override
public int getCount() {
    return M_FRAGMENT_LIST.size();
}