我试图从另一个扩展FragmentStatePagerAdapter的类中获取片段列表的大小,但我不知道如何使用它。如果它是一个内部类我没有问题,但后来使用适配器作为一个单独的类,我不能让它工作。
这是mainActivity
public class MainActivity extends AppCompatActivity {
public List<Fragment> fragmentList = new ArrayList<>();
public List<String> tabTitles = new ArrayList<>();
private TabPagerAdapter pagerAdapter;
private TabLayout tabLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fragmentList.add(Fragment1.newInstance());
fragmentList.add(Fragment2.newInstance());
fragmentList.add(Fragment3.newInstance());
tabTitles.add("Tab 1");
tabTitles.add("Tab 2");
tabTitles.add("Tab 3");
// Setup the viewPager
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
pagerAdapter = new TabPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
// Setup the Tabs
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
// This method ensures that tab selection events update the ViewPager and page changes update the selected tab.
tabLayout.setupWithViewPager(viewPager);
}
这是TabPagerAdapter,我想获得片段列表大小&amp;位置。我该怎么办?
public class TabPagerAdapter extends FragmentStatePagerAdapter {
private MainActivity mMainActivity;
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int pos) {
//this code gives error
return mMainActivity.fragmentList.get(pos);
}
@Override
public int getCount() {
//this line gives error
return mMainActivity.fragmentList.size();
}
答案 0 :(得分:1)
您可以在构造函数中传递fragmentList
引用:
public class TabPagerAdapter extends FragmentStatePagerAdapter {
private MainActivity mMainActivity;
private List<Fragment> fragmentList;
public TabPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {
super(fm);
this.fragmentList = fragmentList;
}
@Override
public Fragment getItem(int pos) {
return fragmentList.get(pos);
}
@Override
public int getCount() {
return fragmentList.size();
}
}
然后你像这样创建TabPagerAdapter
:
pagerAdapter = new TabPagerAdapter(getSupportFragmentManager(), fragmentList);