PagerSlidingTabStrip源码解析

来源:互联网 发布:淘宝店铺年度运营计划 编辑:程序博客网 时间:2024/06/07 09:22

项目简介

项目地址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就是最左边,虽然有可能因为滑动而被挡住,没有显示出来。

0 0