我有一个包含3个标签片段的viewPager。 第一个和第二个片段工作正常但是当我扫到第三个标签时 我没有看到他。 第三个选项卡仅在viewPager的活动重新加载时移动(移动到另一个活动并返回)。
我的代码:
private void setupViewPager(ViewPager viewPager) {
adapter = new PagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Fragment1(), Constants.TAB_0);
adapter.addFragment(new Fragment2(), Constants.TAB_1);
adapter.addFragment(new Fragment3(), Constants.TAB_2);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(3);
}
寻呼机适配器:
public class PagerAdapter extends FragmentPagerAdapter {
/*
* Arraylist used to contain the fragments
* and contain fragments title's
*/
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
//Adds the fragment and it's title. Called in MainActivity
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
//Retrieves the title of the tab
@Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
答案 0 :(得分:1)
这是我的适配器,在getItem上我将片段对象设置为Fragment活动。
public class SectionPagerAdapter extends FragmentPagerAdapter {
Fragment fragment;
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if (position == 0){
fragment = new FragmentOne();
}
else if (position == 1){
fragment = new FragmentTwo();
}
else if (position == 2){
fragment = new FragmentThree();
}
return fragment;
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "name one";
case 1:
return "name two";
case 2:
return "name three";
}
return null;
}
}
然后在我的主要活动中,我称之为:
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
SectionPagerAdapter sectionPagerAdapter = new SectionPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(sectionPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
尝试用上面的代码替换代码,让我知道它是否有帮助!
答案 1 :(得分:0)
USE new PagerAdapter(getChildSupportFragmentManager());
而不是 getSupportFragmentManager()
试试这个!!