Android ViewPager加TabLayout
阿新 • • 發佈:2018-11-08
Android ViewPager加TabLayout
佈局
使用TabLayout需要新增依賴
implementation 'com.android.support:design:26.1.0'
<android.support.v4.view.ViewPager android:id="@+id/vp" android:layout_width="match_parent" android:layout_weight="10" android:layout_height="0dp"></android.support.v4.view.ViewPager> <android.support.design.widget.TabLayout android:id="@+id/tab" android:layout_width="match_parent" android:layout_weight="1" android:layout_height="0dp"></android.support.design.widget.TabLayout>
讓他有三個滑動頁面,需要建立三個Fragment。
當然,當Fragment多時建立那那麼多Fragment有點麻煩,這時也可以採用Fragment複用,我就直接建立三個Fragment了。
Activity主程式碼
TabLayout下標題需要泛型為String的集合
TabLayout tabLayout=findViewById(R.id.tab); ViewPager viewPager=findViewById(R.id.vp); ArrayList<String> title=new ArrayList<>(); title.add("a"); title.add("b"); title.add("c"); ArrayList<Fragment> list=new ArrayList<>(); BlankFragment1 blankFragment1=new BlankFragment1(); BlankFragment2 blankFragment2=new BlankFragment2(); BlankFragment3 blankFragment3=new BlankFragment3(); list.add(blankFragment1); list.add(blankFragment2); list.add(blankFragment3); MyAdapter_vp myAdapter_vp=new MyAdapter_vp(getSupportFragmentManager(),title,list); viewPager.setAdapter(myAdapter_vp); tabLayout.setupWithViewPager(viewPager);
MyAdapter_vp 為ViewPager加TabLayout的介面卡
private ArrayList<String> title; private ArrayList<Fragment> list; public MyAdapter_vp(FragmentManager fm, ArrayList<String> title, ArrayList<Fragment> list) { super(fm); this.title = title; this.list = list; } @Override public Fragment getItem(int position) { return list.get(position); } @Override public int getCount() { return list.size(); } @Override public CharSequence getPageTitle(int position) { return title.get(position); }
OK了,如果有什麼問題可以評論給我!