public class MainActivity extends AppCompatActivity { private ViewPager pager; private TabLayout mytab; private List<String> meuns=new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mytab = findViewById(R.id.mytab); pager=findViewById(R.id.vp); initmeuns(); MyAdapter adapter = new MyAdapter(getSupportFragmentManager()); pager.setAdapter(adapter); //一次初使化所有页面 pager.setOffscreenPageLimit(meuns.size()); //创建关联 mytab.setupWithViewPager(pager); } class MyAdapter extends FragmentPagerAdapter{ public MyAdapter(FragmentManager fm) { super(fm); } @Override public CharSequence getPageTitle(int position) { return meuns.get(position); } @Override public Fragment getItem(int position) { Bundle bundle=new Bundle(); bundle.putString("key",meuns.get(position)); Fragment1 fragment1=new Fragment1(); fragment1.setArguments(bundle); return fragment1; } @Override public int getCount() { return meuns.size(); } } private void initmeuns() { meuns.add("新闻"); meuns.add("社会"); meuns.add("军事"); meuns.add("科技"); meuns.add("财经"); meuns.add("娱乐"); meuns.add("八卦"); meuns.add("二炮"); meuns.add("体育"); meuns.add("明星"); meuns.add("美女"); meuns.add("绯闻"); } }
TabLayout侧滑
最新推荐文章于 2019-02-25 09:43:16 发布