利用TabLayout和fragment搭建app框架
最近闲来无事,就想学习一下android 新出的tablayout控件,原先是用radioGroup+fragment,于是我重新用tablayout+fragment重构了一下。因为tablayout是support design包的,因此需要在build.gradle文件中添加:
compile'com.android.support:design:23.3.0'
按照国际惯例,先上图:

我们先开始写布局
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">
<RelativeLayout android:id="@+id/main_client"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"/>
<android.support.design.widget.TabLayout
android:id="@+id/main_tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/color_title_bar"/>
</LinearLayout>
布局很简单,就包括一个相对布局和一个tablayout控件,写好之后呢,我就想着,tablayout如何设置相应的属性,比如选中某个tab后,下方是否有选中的线,比如下图(这是tabLayout默认的显示效果),如果想更改线的高度,颜色或者直接不让线显示,该怎么办呢?

跟踪tablayout的源码查看,发现tabLayout默认使用Widget_Design_TabLayout这个theme


其中可以看到 tabGravity和tabMode这2个属性,但是我们那个选中的线的颜色和高度在哪呢?注意看它还有个父类,继续跟踪:

看到一个tabIndicatorColor属性,猜想一下,这个是否就是选中线的颜色?那个height是否是选中的线的高度?于是查看一下

发现还真是,高度同理,我就不带着大家看了,因此我们如果想把选中的线的颜色去掉,就可以把高度,设置为0就行了,因此如果想要定制tab的一些属性,比如颜色,选中的字体的颜色等,就可以写下属性:

比如我的项目里,就加了一个style,来得到我需要的效果
其中style为:在res/values/styles目录下
<--主界面tablayout-->
<style name="MainTabLayout">
<item name="tabIndicatorColor">@android:color/transparent </item>
<item name="tabIndicatorHeight">0dp </item>
<item name="tabPaddingStart">12dp </item>
<item name="tabPaddingEnd">12dp </item>
</style>
这些属性具体代表什么意思,请参考 安卓developer

第二步:写activity
因为用到了fragment,所以我这里用到了FragmentPagerAdapter
废话不多说了,直接上代码吧


tabLayout.setTabMode()这个是tab的模式,有4种模式,如下图:

这个模式也可以在xml中设置

因为使用了fragment,所以这里使用了FragmentPagerAdapter来管理fragment
mainPageAdapter

tabLayout已经初始化好了tab,fragment也已经初始化好了,现在需要将fragment与container绑定(container即为相对布局,也就是中间显示的那块),当点击切换tab时,container显示对应的fragment
来实现点击切换tab的操作:
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
Fragment fragment = (Fragment)adapter.instantiateItem(container, position);
adapter.setPrimaryItem(container, pos, fragment);
adapter.finishUpdate(container);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
给tabLayout加个切换的监听,setOnTabSelectedListener这个监听,看名字就能大概猜出来是什么意思,就是当tab页面被选中时,会调用这个方法,当tab页面被选中时,切换目前的fragment。并且将container与fragment联合在一起了
还有一个问题,就是,第一次进页面,如何显示默认选中的页面?
我们看到代码中的initTab中,里面有个

这段代码,就是给tabLayout加上tab,并且后面的第二个参数,当i==0的时候,给了true,其他都是false,查看源码发现,最后会执行下面这段代码:

因此会回调我们写的那个onTabSelected方法,会默认选择第一个
总结:
一、在xml里定义 tabLayout,相对布局
二、在代码里,给tablayout add 上tab,并且写上一个用于管理fragment的adapter
三、给tablayout加个监听,用于切换tab时,显示切换的那个fragment
注意:
要在fragment里面,加上这段代码,如果不加的话,会出现fragment重叠的现象,

跟踪下 adapter.setPrimaryItem(mContainer, pos, fragment) 源码,

发现这段代码是用来控制哪个fragment'显示,哪个隐藏,所以要在每个fragment里加上 那段代码,否则都会显示,就出现重叠的现象
终于写完了,类似我了,