使用TabLayout和ViewPager实现左右滑动选项卡

来源:互联网 发布:免费的晶体结构数据库 编辑:程序博客网 时间:2024/05/20 18:48

        很多项目中需要Avtivity或Fragment使用分页来显示更多内容,今天记录一种比RadioGroup点击换页更为好一些TabLayout换页方法(个人观点)。

步骤很简单:1、在XML 布局文件中放入控件

<android.support.design.widget.TabLayout    android:id="@+id/tl_production"    android:layout_width="match_parent"    android:layout_height="wrap_content"></android.support.design.widget.TabLayout><android.support.v4.view.ViewPager    android:id="@+id/vp_production"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_below="@id/tl_production"></android.support.v4.view.ViewPager>
 2、在Activity中如下,如果是Fragment可以在onCreateView() 中写。

private ViewPager vp_production;private TabLayout tl_production;private ProductionAdapter pAdapter;private List<Fragment> fragment_list;private List<String> list_title;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_layout);    vp_production = (ViewPager) findViewById(R.id.vp_production);    tl_production = (TabLayout) findViewById(R.id.tl_production);    tl_production.setTabMode(TabLayout.MODE_FIXED);    fragment_list = new ArrayList<>();    fragment_list.add(new Fragment());//这里使用Fragment作为选项页    fragment_list.add(new SecondFragment());    list_title = new ArrayList<>();    list_title.add("第一页");    list_title.add("第二页");    tl_production.addTab(tl_production.newTab().setText(list_title.get(0)));    tl_production.addTab(tl_production.newTab().setText(list_title.get(1)));
    pAdapter = new ProductionAdapter(getSupportFragmentManager(), fragment_list, this, list_title);    vp_production.setAdapter(pAdapter);    tl_production.setupWithViewPager(vp_production);}

一下是一些其他相关的知识:


TabLayout样式改变

设置指示器颜色:需要注意的是要在父布局中加上

xmlns:app="http://schemas.android.com/apk/res-auto"
“app:”才能使用

<android.support.design.widget.TabLayout
<!--这里设置指示器的颜色-->
app:tabIndicatorColor="@color/colorBlack"
android:id="@+id/tl_production" android:layout_width="match_parent" android:layout_height="wrap_content"></android.support.design.widget.TabLayout>
其他相关的属性可以点出来试试。关于设置TabLayout中文字的大小并没有直接可用的属性,不过网上有文章,链接留下需要时可以参考http://blog.csdn.net/wode_dream/article/details/50424446









0 1
原创粉丝点击