項目簡介
項目地址https://github.com/astuetz/PagerSlidingTabStrip
該項目是一個配合ViewPager使用的指示器控件,這裏的ViewPager的adapter必須是繼承FragmentPagerAdapter,且需要重寫getPageIconResId(int position)或者getPageTitle(int position)以便指示器顯示內容。
使用方法
首先在佈局文件中包含PagerSlidingTabTrip和ViewPager
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.astuetz.PagerSlidingTabStrip
android:id="@+id/indicator"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="#fff5f5f5"
android:textSize="16sp"
android:textColor="@drawable/selector_indicator_text_color"
app:pstsShouldExpand="true"
app:pstsIndicatorHeight="4dp"
app:pstsIndicatorColor="@color/red"
app:pstsUnderlineHeight="0dp"
app:pstsDividerColor="#fff5f5f5"/>
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
然後綁定ViewPager
indicator = (PagerSlidingTabStrip) findViewById(R.id.indicator);
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(new FragmentAdapter(getFragmentManager()));
indicator.setViewPager(viewPager);
這裏需要注意的是如果要爲ViewPager設置OnPageChangeListener應該設置在indicator裏,而不是直接爲ViewPager設置,至於爲什麼下面會解釋。
源碼解析
從構造方法開始
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();
rectPaint = new Paint();
rectPaint.setAntiAlias(true);
rectPaint.setStyle(Style.FILL);
dividerPaint = new Paint();
dividerPaint.setAntiAlias(true);
dividerPaint.setStrokeWidth(dividerWidth);
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;
}
}
在構造方法中先是new了一個LinearLayout作爲tab的容器,然後取得一些屬性,完成了一些初始化操作。
接下來看一下setViewPager(ViewPager pager)方法
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();
}
這裏將viewpager保存起來,然後設置listener,不過這裏的listener是一個內部類,等下再來分析這個類,在該方法的最後調用方法notifyDataSetChanged(),我們來看一下
public void notifyDataSetChanged() {
tabsContainer.removeAllViews();
tabCount = pager.getAdapter().getCount();
for (int i = 0; i < tabCount; i++) {
if (pager.getAdapter() instanceof IconTabProvider) {
addIconTab(i, ((IconTabProvider) pager.getAdapter()).getPageIconResId(i));
} else {
addTextTab(i, pager.getAdapter().getPageTitle(i).toString());
}
}
......
}
這裏主要完成tab的初始化,沒有什麼難度。接下來就是比較重要的PageListener類了
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();
if (delegatePageListener != null) {
delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
scrollToChild(pager.getCurrentItem(), 0);
}
if (delegatePageListener != null) {
delegatePageListener.onPageScrollStateChanged(state);
}
}
@Override
public void onPageSelected(int position) {
if (delegatePageListener != null) {
delegatePageListener.onPageSelected(position);
}
}
}
該控件提供一個setOnPageChangeListener()方法允許用戶設置自己的Listener,然後在PageListener類中每個方法都會在listener非空 的情況下調用相應方法。
在ViewPager滑動的時候調用scrollToChild方法滑動自身,然後通過invalidata觸發onDraw繪製indicator。
繪製的主要代碼爲
......
if (currentPositionOffset > 0f && currentPosition < tabCount - 1) {
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);
}
canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint);
......
改變一下就可以發現
lineLeft = lineLeft + (nextTabLeft - lineLeft) * currentPositionOffset
lineRight = lineRight + (nextTabRight - lineRight) * currentPositionOffset
而且nextTabLeft - lineLeft就是當前tab的width,nextTabRight - lineRight是下一個tab的width
所以最後就是
lineLeft = lineLeft + currentWidth * currentPositionOffset
lineright = lineRight + nextWidth * currentPositionOffset
這樣的寫法可以動態改變indicator的width。
值得注意的是我們發現在無論是scrollToChild()還是onDraw()中都用的是tab.getLeft(),那麼我們一個一個來分析。
在scrollToChild()中,是使用scrollTo()滑動scrollview,tab.getLeft()得到的是相對於父控件的距離,也就是相對於LinearLayout的距離,這樣無論怎麼滾動,任何tab的left都是不會變的,因爲是相對於LinearLayout的距離,而LinearLayout是不會變的。然後根據該left加上偏移量去scrollTo(),就會正好向左滑動讓tab靠在最左邊。
onDraw()中主要是爲了繪製indicator,canvas的繪製應該是繪製在本身的,也就是繪製在HorizontalScrollView上的,經過試驗發現如果我們draw的left爲0,那麼會顯示在LinearLayout的最左邊,也就是說left爲0的位置並不是在顯示的最左端,而是實際上內容的最左端,可以把整個控件想象爲完全展開的,left就是最左邊,雖然有可能因爲滑動而被擋住,沒有顯示出來。