@Override public Fragment getItem(int position) { switch (position) { case 0: tab1 tab1 = new tab1(); return tab1; case 1: tab2 tab2 = new tab2(); return tab2; case 3: // Should be 2 tab3 tab3 =new tab3(); return tab3; default: return null ; }
首先,纠正你的 的 CASE 强> 部分。
CASE
case 2: tab3 tab3 =new tab3(); return tab3;
这个问题有另一个解决方案
private ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.container); setupViewPager(mViewPager); //Replace your line to this TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); } //method for adding fragment to the adapter private void setupViewPager(ViewPager viewPager) { SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new TabOne(), "ONE"); adapter.addFragment(new TabSecond(), "TWO"); adapter.addFragment(new TabThird(), "THREE"); viewPager.setAdapter(adapter); } public class SectionsPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public SectionsPagerAdapter(FragmentManager fm) { super(fm); } // add this method in your adapter public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } }
}