最近在弄一些常用的好看的控件,当然少不了ViewPager,然后ViewPager通常要和标签组合使用,在很就之前我是用RadioGroup来当作标签的,然后发现了ViewPagerIndicator,但用起来很麻烦,但效果很多样化。但最终我选择了使用PagerSlidingTabStrip
原因有以下两点
1. 加载简单
2. 使用简单
加载只需在Moudle的Build.gradle里添加
compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
使用的话也是非常简单
<com.astuetz.PagerSlidingTabStrip
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@color/colorPrimary"
app:pstsIndicatorColor="@color/colorAccent"
app:pstsIndicatorHeight="4dp"
android:textColor="#fff"
android:textSize = "18sp"
app:pstsShouldExpand="true"
android:id="@+id/header">
参照官方的使用说明
主要属性有以下几点
- pstsIndicatorColor Color of the sliding indicator 底部indicator的颜色
- pstsUnderlineColor Color of the full-width line on the bottom of the view 底部横线的颜色
- pstsDividerColor Color of the dividers between tabs 左右分割线的颜色
- pstsIndicatorHeightHeight of the sliding indicator 底部indicator的高度
- pstsUnderlineHeight Height of the full-width line on the bottom of the view 底部横线的高度
- pstsDividerPadding Top and bottom padding of the dividers 左右分割线距离上下的宽度
- pstsTabPaddingLeftRight Left and right padding of each tab 左右分割线距离左右的宽度
- pstsScrollOffset Scroll offset of the selected tab
- **pstsTabBackground **Background drawable of each tab, should be a StateListDrawable 标签背景//通常自定义点中和没点中的样式
- pstsShouldExpand If set to true, each tab is given the same weight, default false 设置标签是否等宽
- pstsTextAllCaps If true, all tab titles will be upper case, default true 标题是否都是大写
只需在控件里设置属性就好,不用像ViewPagerIndicator那样设置一堆Theme
然后回到Activity,在onCreate方法里绑定相应的ViewPager和PagerSlidingTabStrip
ViewPager pager;
PagerSlidingTabStrip header;
pager= (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(new PagerAdapter(getSupportFragmentManager()));
header= (PagerSlidingTabStrip) findViewById(R.id.header);
header.setViewPager(pager);
PagerAdapter是要自己新建一个继承自FragmentPagerAdapter的类
private class PagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = getResources().getStringArray(R.array.pager_name);
private PagerAdapter(FragmentManager fm) {
super(fm);
}
//设置标签标题
@Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
@Override
public Fragment getItem(int position) {
Bundle bundle = new Bundle();
//通常都是用Fragment的List,我这里采用相同的样式
BlankFragment pagerFragment=new BlankFragment();
//根据不同的postion传递不同信息
bundle.putInt("page_num", position);
pagerFragment.setArguments(bundle);
return pagerFragment;
}
@Override
public int getCount() {
return TITLES.length;
}
}
PagerSlidingTabStrip其实基本上可以满足我们平常开发的需求,他简单的使用也是很受初学者青睐的。