简介
PagerSlidingTabStrip,是我个人经常使用到的一个和ViewPager配合的页面指示器,可以满足开发过程中常用的需求,如类似于今日头条的首页新闻内容导航栏等等,之前自己开发的JuheNews和正在开发的GankIOClient均有使用到它,所以想对其进行一个全面的介绍。
PagerSlidingTabStrip源码地址:
https://github.com/astuetz/PagerSlidingTabStrip
简单使用
- 添加库依赖
dependencies {
compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
}
- 1
- 2
- 3
- 定义布局文件
<com.astuetz.PagerSlidingTabStrip
android:id="@+id/psts_indicator"
android:layout_width="match_parent"
android:layout_height="40dp"/>
<android.support.v4.view.ViewPager
android:id="@+id/vp_content"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 关联ViewPager
public class MainActivity extends AppCompatActivity {
@BindView(R.id.psts_indicator)
PagerSlidingTabStrip pstsIndicator;
@BindView(R.id.activity_main)
LinearLayout activityMain;
@BindView(R.id.vp_content)
ViewPager vpContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
MainPagerAdapter mainPagerAdapter = new MainPagerAdapter(getSupportFragmentManager());
vpContent.setAdapter(mainPagerAdapter);
pstsIndicator.setViewPager(vpContent);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 结果
- 后话
看到这个效果,是不是很炸裂,如此的丑陋,上图是什么属性都没有修改默认的效果图,接着我们看下源码,看下可以从哪方面来进行改造。
源码解析
这个开源库,简单点说就是大家都非常熟悉的自定义View,所以,解读的方式可以从自定义属性到此视图的构造,onMeasure,onLayout, onDraw等等
1. 自定义的属性值
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="PagerSlidingTabStrip">
<!--底部滑动指示器的颜色-->
<attr name="pstsIndicatorColor" format="color" />
<!--底部用于给指示器滑动的区域的颜色-->
<attr name="pstsUnderlineColor" format="color" />
<!--分割线的颜色-->
<attr name="pstsDividerColor" format="color" />
<!--指示器的高度-->
<attr name="pstsIndicatorHeight" format="dimension" />
<!--底部区域的高度-->
<attr name="pstsUnderlineHeight" format="dimension" />
<!--分割线与上下的间距-->
<attr name="pstsDividerPadding" format="dimension" />
<!--每个Tab的左右边距-->
<attr name="pstsTabPaddingLeftRight" format="dimension" />
<!--选中tab的滚动偏移量,个人基本没有用到过-->
<attr name="pstsScrollOffset" format="dimension" />
<!--每个Tab的背景图,StateListDrawable-->
<attr name="pstsTabBackground" format="reference" />
<!--是否根据tab均为位置,true的时候均分,默认为false,一般都是使用默认值-->
<attr name="pstsShouldExpand" format="boolean" />
<!--标题文本是否大写,默认为true-->
<attr name="pstsTextAllCaps" format="boolean" />
</declare-styleable>
</resources>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
看下大致的布局和属性对号入座
2. PagerSlidingTabStrip.java类结构
类中的getter和setter方法,基本上和上面的自定义属性可以对上号,不仅可以在布局文件中定义,还可以通过java代码进行设置。
类中使用到的变量,大部分都是和自定义属性挂钩的,主要关注几个
变量 | 意义 |
---|---|
ATTRS | 引用Android系统的两个属性,文本字体大小和字体颜色 |
pageListener | 内部使用的OnPagerChangeListener,通过setViewPager实现和ViewPager的联动 |
delegatePageListener | 暴露给开发者的接口,类本身使用到了两个OnPageChangeListener,一个用来实现自己的逻辑,而这个则是留给开发者实现自己需要针对ViewPager的页面变化的逻辑 |
tabsContainer | 内部容器,用户所见文本指示器和图标指示器的父节点,所以,如果需要针对文本指示器或者是图标指示器做什么操作,通过这个查找孩子节点即可 |
IconTabProvider
类中比较关键的一些内容,接口IconTabProvider,ViewPager对应的Adapter实现该方法并返回每个ViewPager对应的图标即可实现图标指示器。PageListener <用户自定义的OnPagerListener的事件处理集成于此处>
private class PageListener implements OnPageChangeListener {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//存储当前位置信息
currentPosition = position;
currentPositionOffset = positionOffset;
//滑动到子视图
scrollToChild(position, (int) (positionOffset * tabsContainer.getChildAt(position).getWidth()));
invalidate();//触发重绘
//用户自定义的OnPagerChangeListener事件之onPagerScrolled
if (delegatePageListener != null) {
delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
@Override
public void onPageScrollStateChanged(int state) {
//已经滑动完成,offset归0
if (state == ViewPager.SCROLL_STATE_IDLE) {
scrollToChild(pager.getCurrentItem(), 0);
}
//用户自定义的OnPagerChangeListener事件之onPageScrollStateChanged
if (delegatePageListener != null) {
delegatePageListener.onPageScrollStateChanged(state);
}
}
@Override
public void onPageSelected(int position) {
//这里类内部没有做什么处理,只处理用户自定义的OnPagerSelected方法
if (delegatePageListener != null) {
delegatePageListener.onPageSelected(position);
}
}
}
/**
*滑动指定子视图
*/
private void scrollToChild(int position, int offset) {
if (tabCount == 0) {
return;
}
int newScrollX = tabsContainer.getChildAt(position).getLeft() + offset;
if (position > 0 || offset > 0) {
newScrollX -= scrollOffset;
}
if (newScrollX != lastScrollX) {
lastScrollX = newScrollX;
scrollTo(newScrollX, 0);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- PagerSlidingTabStrip构造方法
构造方法的内容不多,基本上全是基本属性的获取,自定义View中常用的TypedArray ,记得回收recycle(),这里关注一下 TypedValue.applyDimension方法的使用,全部转换成px。
public PagerSlidingTabStrip(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFillViewport(true);
setWillNotDraw(false);
tabsContainer = new LinearLayout(context);
tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
addView(tabsContainer);
DisplayMetrics dm = getResources().getDisplayMetrics();
scrollOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm);
indicatorHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm);
underlineHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm);
dividerPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm);
tabPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm);
dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm);
tabTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm);
// get system attrs (android:textSize and android:textColor)
TypedArray a = context.obtainStyledAttributes(attrs, ATTRS);
tabTextSize = a.getDimensionPixelSize(0, tabTextSize);
tabTextColor = a.getColor(1, tabTextColor);
a.recycle();
// get custom attrs
a = context.obtainStyledAttributes(attrs, R.styleable.PagerSlidingTabStrip);
indicatorColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsIndicatorColor, indicatorColor);
underlineColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsUnderlineColor, underlineColor);
dividerColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsDividerColor, dividerColor);
indicatorHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsIndicatorHeight, indicatorHeight);
underlineHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsUnderlineHeight, underlineHeight);
dividerPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsDividerPadding, dividerPadding);
tabPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsTabPaddingLeftRight, tabPadding);
tabBackgroundResId = a.getResourceId(R.styleable.PagerSlidingTabStrip_pstsTabBackground, tabBackgroundResId);
shouldExpand = a.getBoolean(R.styleable.PagerSlidingTabStrip_pstsShouldExpand, shouldExpand);
scrollOffset = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsScrollOffset, scrollOffset);
textAllCaps = a.getBoolean(R.styleable.PagerSlidingTabStrip_pstsTextAllCaps, textAllCaps);
a.recycle();
/* 初始化矩形Paint */
rectPaint = new Paint();
rectPaint.setAntiAlias(true);
rectPaint.setStyle(Style.FILL);
/* 初始化分割线Paint */
dividerPaint = new Paint();
dividerPaint.setAntiAlias(true);
dividerPaint.setStrokeWidth(dividerWidth);
/* 是否延伸,默认WRAP_CONTENT,这种比较合理 */
defaultTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
expandedTabLayoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f);
if (locale == null) {
locale = getResources().getConfiguration().locale;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- onDraw
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isInEditMode() || tabCount == 0) {
return;
}
final int height = getHeight();
// 设置Indicator颜色
rectPaint.setColor(indicatorColor);
// 获取当前选中Tab
View currentTab = tabsContainer.getChildAt(currentPosition);
//获取Left,Right值
float lineLeft = currentTab.getLeft();
float lineRight = currentTab.getRight();
// if there is an offset, start interpolating left and right coordinates between current and next tab
if (currentPositionOffset > 0f && currentPosition < tabCount - 1) {
//结合下一个Tab获取当前要绘制的indicator的位置,这里的currentPositionOffset 比较关键,可以看到这个值是与ViewPager相关的,在onPagerScrolled方法中,这个值在不断的更新
View nextTab = tabsContainer.getChildAt(currentPosition + 1);
final float nextTabLeft = nextTab.getLeft();
final float nextTabRight = nextTab.getRight();
lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft);
lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight);
}
// 绘制Indicator
canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint);
// 绘制UnderLine
rectPaint.setColor(underlineColor);
canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint);
// 绘制分割线
dividerPaint.setColor(dividerColor);
for (int i = 0; i < tabCount - 1; i++) {
View tab = tabsContainer.getChildAt(i);
canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(), height - dividerPadding, dividerPaint);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- setViewPager, setOnPageChangeListener
一个用来与ViewPager联动,一个用来处理自定义的OnPagerListener逻辑
public void setViewPager(ViewPager pager) {
this.pager = pager;
if (pager.getAdapter() == null) {
throw new IllegalStateException("ViewPager does not have adapter instance.");
}
pager.setOnPageChangeListener(pageListener);
notifyDataSetChanged();
}
public void setOnPageChangeListener(OnPageChangeListener listener) {
this.delegatePageListener = listener;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
3. PagerSlidingTabStrip综合用法
- 文本指示器选中后文本大小和颜色变化
关键点在于实现自己的OnPagerListener
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
MainPagerAdapter mainPagerAdapter = new MainPagerAdapter(getSupportFragmentManager());
vpContent.setAdapter(mainPagerAdapter);
pstsIndicator.setViewPager(vpContent);
vpContent.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
updateTextStyle(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
updateTextStyle(vpContent.getCurrentItem());
}
private void updateTextStyle(int position) {
LinearLayout tabsContainer = (LinearLayout) pstsIndicator.getChildAt(0);
for(int i=0; i< tabsContainer.getChildCount(); i++) {
TextView textView = (TextView) tabsContainer.getChildAt(i);
if(position == i) {
textView.setTextSize(18);
textView.setTextColor(getResources().getColor(R.color.colorToolbar));
} else {
textView.setTextSize(12);
textView.setTextColor(getResources().getColor(R.color.colorBlack));
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
-
图标指示器选中图标颜色变化
关键点在于实现自己的OnPagerListener和继承PagerSlidingTabStrip.IconTabProvider
private void updateIconStyle(int position) {
LinearLayout tabsContainer = (LinearLayout) pstsIndicator.getChildAt(0);
for (int i = 0; i < tabsContainer.getChildCount(); i++) {
ImageButton imageButton = (ImageButton) tabsContainer.getChildAt(i);
imageButton.setImageTintMode(PorterDuff.Mode.SRC_IN);
if (i == position) {
imageButton.setImageTintList(getResources().getColorStateList(R.color.ib_color_list));
} else {
imageButton.setImageTintList(getResources().getColorStateList(R.color.ib_color_list_normal));
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
4. 写在最后的话
PagerSlidingTabStrip,总体来说简洁方便,如果开发者想集成自己的一些内容,比如说Indicator改成其他的形状,或者说想做到既有文字又有图片的效果,都可以自己修改代码来实现,比较的方便。