2017-09-15 85 views
0

我有一個viewPager,它包含3個標籤片段。 第一個和第二個片段工作正常,但當我掃到第三個標籤 我沒有看到他。 第三個選項卡僅當viewPager的活動重新加載時才顯示(移動到另一個活動並返回)。Android - 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; 
} 

}

+1

'viewPager.setOffscreenPageLimit(2);' –

+0

仍然不起作用 –

回答

1

這裏是我的適配器上的getItem我設置片段對象的片段活動。

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); 

嘗試用上述更換你的代碼,讓我知道,如果有幫助!

+0

這是否適合您? @stav elmashally –

+0

我試過了,仍然沒有改變 –

0

使用new PagerAdapter(getChildSupportFragmentManager());,而不是getSupportFragmentManager()

試試這個!