Android中TabLayout+ViewPager实现tab和页面联动效果
程序员文章站
2023-12-05 23:37:34
tablayout+viewpager实现tab和页面联动效果
xml中:
tablayout+viewpager实现tab和页面联动效果
xml中:
<?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.tablayout android:id="@+id/toolbar_tl_tab" android:layout_width="match_parent" android:layout_height="?attr/actionbarsize" android:layout_gravity="bottom" app:layout_scrollflags="scroll" app:tabindicatorcolor="@android:color/holo_green_light" app:tabselectedtextcolor="@android:color/holo_green_light" /> <view android:layout_width="match_parent" android:layout_height="1dp" android:background="#f0f0f0" /> <android.support.v4.view.viewpager android:id="@+id/vp_container" android:layout_width="match_parent" android:layout_height="match_parent" /> </relativelayout>
代码中使用:
public class mainactivity extends appcompatactivity { private tablayout toolbar_tl_tab; private viewpager vp_container; private string[] titles = {"标题1", "标题2", "标题3", "标题4"}; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); init(); } private void init() { toolbar_tl_tab = (tablayout) findviewbyid(r.id.toolbar_tl_tab); vp_container = (viewpager) findviewbyid(r.id.vp_container); toolbar_tl_tab.setupwithviewpager(vp_container); toolbar_tl_tab.settabmode(tablayout.mode_scrollable); vp_container.setadapter(new fragmentstatepageradapter(getsupportfragmentmanager()) { @override public fragment getitem(int position) { return new pagefragment(); } @override public charsequence getpagetitle(int position) { return titles[position]; } @override public int getcount() { return titles.length; } }); } }
碎片:pagefragment
public class pagefragment extends fragment { @nullable @override public view oncreateview(layoutinflater inflater, @nullable viewgroup container, @nullable bundle savedinstancestate) { view view = inflater.inflate(r.layout.fragment_page, null); return view; } }
碎片xml:fragment_page.xml
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <textview android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="页面" /> </linearlayout>
注意:
1、模式相关
使用滚动模式,特点是超过屏幕可以滚动显示:
toolbar_tl_tab.settabmode(tablayout.mode_scrollable);
使用屏幕等分模式,特点是显示tab的宽度是屏幕等分后的宽度:
toolbar_tl_tab.settabmode(tablayout.mode_fixed);
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: IBM T43机器死机故障一例