谷歌在Material Design中推出TabLayout以替代开源库PagerSlidingTabStrip和ViewPagerIndicator的使用。事实上,这类indicator指示器的布局可谓是android中最常见的布局设计了,TabLayout的出现给我们带来一定便利,它的使用对开发者更加友好,并且和Toolbar一样,配合material design的其他控件使用能轻易创造出酷炫的效果,下面我们快来学习它。
一、创建布局
使用TabLayout时,常与ViewPager一起关联使用,布局如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"/>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"/>
</LinearLayout>
注意TabLayout中的tabMode属性可选scrollable或fixed:
- scrollable可以滑动,向左对齐,如今日头条,网易新闻就是scrollable,但是在Tab选项卡较少时会无法填满TabLayout栏。
- fixed则无法滑动,每个选项卡平均分配空间,适合较少Tab选项卡的情况,当选项卡较多时,会出现每个选项卡内容无法显示完整的情况,请大家大家根据情况选择。
也可在代码中使用以下方法设置。
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
或
tabLayout.setTabMode(TabLayout.MODE_FIXED);
还有另一个比较类似的属性是app:tabGravity可选fill或centre:
- 当选项卡很少需要置于中心时,就需要用到centre,可以参考简书手机App首页标题栏“文章”,“专题”两个选项卡的居中效果。
- 当选项卡需要填满TabLayout布局时,则用到fill。
二、创建Fragment
public class PageFragment extends android.support.v4.app.Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment pageFragment = new PageFragment();
pageFragment.setArguments(args);
return pageFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_page, container, false);
TextView textView = (TextView) view;
textView.setText("Fragment #" + mPage);
return view;
}
}
Fragment的布局为
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
</TextView>
没什么说的,布局是一个简单的TextView,通过实例化Fragment传递参数。
三、创建ViewPager的适配器
public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter {
private Context context;
private static final String[] mTitles = {"tab1", "tab2", "tab3"};
public SimpleFragmentPagerAdapter(FragmentManager fm,Context context) {
super(fm);
this.context = context;
}
@Override
public android.support.v4.app.Fragment getItem(int position) {
return PageFragment.newInstance(position + 1);
}
@Override
public int getCount() {
return mTitles.length;
}
@Override
public CharSequence getPageTitle(int position) {
return mTitles[position];
}
}
四、在MainActivity中设置TabLayout
public class ThirdActivity extends FragmentActivity {
private SimpleFragmentPagerAdapter pagerAdapter;
private ViewPager viewPager;
private TabLayout tabLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
pagerAdapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), this);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
pagerAdapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(),this);
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
}
五、自定义TabLayout样式
你应该不会满足于现在的TabLayout,实际应用中,往往会改变TabLayout的背景,字体大小和颜色,指示标的宽度和颜色等等。
在MainActivity布局下给TabLayout添加一个style如下:
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
style="@style/tab_style"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"/>
并且在styles中添加一个样式:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="tab_style" parent="Widget.Design.TabLayout">
<!--<item name="tabMaxWidth">@dimen/tab_max_width</item>-->
<item name="tabPaddingStart">12dp</item>
<item name="tabPaddingEnd">12dp</item>
<item name="tabIndicatorColor">@color/colorAccent</item>
<item name="tabIndicatorHeight">4dp</item>
<item name="tabTextAppearance">@style/CustomTabTextAppearance</item>
<item name="tabBackground">@color/colorPrimary</item>
<item name="tabSelectedTextColor">@color/colorAccent</item>
</style>
<style name="CustomTabTextAppearance" parent="TextAppearance.Design.Tab">
<item name="android:textSize">18sp</item>
<item name="android:textColor">#FFFFFF</item>
<item name="textAllCaps">false</item>
</style>
</resources>
注意这里的@color/colorAccent是粉色,@color/colorPrimary是蓝色。
各个属性所代表的含义:
1.tabMaxWidth:tab item的最大宽度,当app:tabMode="fixed"时不起作用,当app:tabMode="fixed"时才起作用。其中:
2.tabIndicatorColor:TabLayout指示器的颜色
3.tabIndicatorHeight:TabLayout指示器高度
4.tabPaddingStart:距离开始的长度
5.tabPaddingEnd:距离结束的长度
6.tabBackground:TabLayout背景
7.tabTextAppearance:TabLayout title字体属性
8.tabSelectedTextColor:当前选择的tab的字体颜色
9.textAllCaps:TabLayout创建的Tab默认的是true,如果设置图标的话要设置成false。
这时再运行看下效果:
六、添加icon到tab
当前的TabLayout没有方法让我们去添加icon,我们可以使用SpannableString结合ImageSpan来实现,在SimpleFragmentPagerAdapter中:
//自己随便从官网找几个icon吧
private static final int[] mImgIds = {R.drawable.ic_stars_black_18dp,
R.drawable.ic_supervisor_account_black_24dp,
R.drawable.ic_today_black_24dp
};
//...
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
// return tabTitles[position];
Drawable image = context.getResources().getDrawable(mImgIds[position]);
image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
SpannableString sb = new SpannableString(" ");
ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return sb;
}
再运行可以看到:
如果要同时把icon和text添加到tab同理,把getPageTitle()方法改为:
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
Drawable image = context.getResources().getDrawable(mImgIds[position]);
image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
// Replace blank spaces with image icon
SpannableString sb = new SpannableString(" " + mTitles[position]);
ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return sb;
}
七、添加自定义的view到tab
1、自定义一个简单的tab布局tab_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
<ImageView
android:id="@+id/iv_tab"
android:layout_width="30dp"
android:scaleType="fitXY"
android:layout_height="30dp"/>
<TextView
android:id="@+id/tv_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" />
</LinearLayout>
2、在适配器中增加getTabView(...)方法:
public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter {
private Context context;
private static final String[] mTitles = {"tab1", "tab2", "tab3"};
private static final int[] mImgIds = {
R.drawable.ic_today_black_24dp,
R.drawable.ic_supervisor_account_black_24dp,
R.drawable.ic_stars_black_18dp
};
public SimpleFragmentPagerAdapter(FragmentManager fm,Context context) {
super(fm);
this.context = context;
}
@Override
public android.support.v4.app.Fragment getItem(int position) {
return PageFragment.newInstance(position + 1);
}
@Override
public int getCount() {
return mTitles.length;
}
@Override
public CharSequence getPageTitle(int position) {
// return mTitles[position];
return null;
}
public View getTabView(int position) {
View view = LayoutInflater.from(context).inflate(R.layout.tab_layout, null);
ImageView iv_tab = (ImageView) view.findViewById(R.id.iv_tab);
TextView tv_tab = (TextView) view.findViewById(R.id.tv_tab);
iv_tab.setImageResource(mImgIds[position]);
tv_tab.setText(mTitles[position]);
return view;
}
}
3、在MainActivity中使用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
pagerAdapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(),this);
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
//获得到对应位置的Tab
TabLayout.Tab tab = tabLayout.getTabAt(i);
//设置自定义的标题
if (tab != null) {
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
}
效果如下图:
八、处理配置改变
当屏幕旋转或者配置改变的时候,我们需要保存当前的状态。
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(POSITION,tabLayout.getSelectedTabPosition());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
viewPager.setCurrentItem(savedInstanceState.getInt(POSITION));
}
关于TabLayout的讲解到此结束,当AppBar包裹Toolbar和TabLayout时,会有更好的效果。另外,设置自定义view后,自定义的style中tabSelectedTextColor就失效了,只找到了用selector使tab切换时图片改变颜色的方法,没找到改变文字颜色的方法,请各位有识之士不吝赐教。
本文参考文章:
android design library提供的TabLayout的用法
Android TabLayout 浅显总结