自定義TabLayout(背景滑塊)

前言:

這個(gè)是與上篇 ViewPager指示器(三角形) 一個(gè)版本做的效果主要的滑動(dòng)原理大致相同囚似,話(huà)不多說(shuō)先看效果弱睦。

藍(lán)色滑塊.gif

  • 這個(gè)用TabLayout是無(wú)法實(shí)現(xiàn)的只能自己寫(xiě)自定義的,當(dāng)時(shí)在網(wǎng)上找了很多都不是自己想要的,后再在github上找到一個(gè)跟我要的很相近的就拿過(guò)來(lái)改了改濒蒋。

實(shí)現(xiàn)思路

  • 我是用的HorizontalScrollView惕味,在HorizontalScrollView添加一個(gè)LinearLayout楼誓,文字和動(dòng)態(tài)圖我寫(xiě)了一個(gè)itemView,再把itemView Add到LinearLayout里。
    1.先把ItemView寫(xiě)好名挥。
    2.ItemView添加到LinearLayout容器里慌随。
    3.獲取當(dāng)Item的寬高,繪制藍(lán)色背景躺同。
    4.計(jì)算滑動(dòng)距離并在ViewPager的滑動(dòng)事件調(diào)用阁猜。

實(shí)現(xiàn)步驟 (主要為核心代碼,全部代碼在最后面)

1. ItemView里多了個(gè)顏色漸變的方法蹋艺,沒(méi)有什么需要說(shuō)的直接貼代碼了剃袍。
public class BusinessTabItemView extends LinearLayout {
    private Context mContext;
    private GifImageView iv_icon;
    private TextView tv_name;
    private static final int COLOR_DEFAULT = Color.parseColor("#555555");
    private static final int COLOR_SELECT = Color.parseColor("#ffffff");

    public BusinessTabItemView(Context context) {
        super(context);
        mContext=context;
        init(context);
    }

    /**
     * 初始化
     * @param context
     */
   private void init(@NonNull final Context context) {
        inflate(context, R.layout.item_business_tab, this);
        iv_icon = findViewById(R.id.iv_icon);
        tv_name = findViewById(R.id.tv_name);
    }

    /**
     * 設(shè)置數(shù)據(jù)
     * @param tag
     * @param isChoice
     */
    public void setData(BusinessTag tag, boolean isChoice){
        tv_name.setText(tag.name);
        if (isChoice){
            tv_name.setTextColor(ContextCompat.getColor(mContext,R.color.white));
            iv_icon.setVisibility(VISIBLE);
            iv_icon.setImageResource(getGifIconID(tag.code));
            GifDrawable gifDrawable =  (GifDrawable) iv_icon.getDrawable();
            gifDrawable.setLoopCount(1);
        }else {
            iv_icon.setVisibility(GONE);
            tv_name.setTextColor(ContextCompat.getColor(mContext,R.color.common_text_55));
        }
    }

    /**
     * 設(shè)置選中
     * @param tag
     * @param isChoice
     */
    public void setChoice(BusinessTag tag, boolean isChoice){
        if (isChoice){
            tv_name.setTextColor(ContextCompat.getColor(mContext,R.color.white));
            iv_icon.setVisibility(VISIBLE);
            iv_icon.setImageResource(getGifIconID(tag.code));
            GifDrawable gifDrawable =  (GifDrawable) iv_icon.getDrawable();
            gifDrawable.setLoopCount(1);
        }else {
            iv_icon.setVisibility(GONE);
            tv_name.setTextColor(ContextCompat.getColor(mContext,R.color.common_text_55));
        }
    }

    /**
     * 通過(guò)code獲取GifIcon的id
     *
     * @param code
     * @return
     */
   private int getGifIconID(String code) {
        int icon = R.drawable.business_tag_qcp;
        switch (code) {
            case GlobalUrlConfig.businesscode_qcp:
                //汽車(chē)票
                icon = R.drawable.gif_business_tag_qcp;
                break;
            case GlobalUrlConfig.businesscode_zx:
                //專(zhuān)線(xiàn)
                icon = R.drawable.gif_business_tag_dzzx;
                break;
            case GlobalUrlConfig.businesscode_hcp:
                //火車(chē)票
                icon = R.drawable.gif_business_tag_hcp;
                break;
            default:
                break;
        }
        return icon;
    }
    /**
     * 設(shè)置字體漸變
     * @param progress
     */
    public void setProgress(float progress) {
        if (progress == 0) {
            tv_name.setVisibility(VISIBLE);
        }
        tv_name.setTextColor(evaluate(progress, COLOR_DEFAULT, COLOR_SELECT));
    }
    /**
     * 顏色漸變器,返回漸變的顏色值
     *
     * @param fraction   進(jìn)度
     * @param startValue
     * @param endValue
     * @return
     */
    private int evaluate(float fraction, int startValue, int endValue) {
        int startInt = (Integer) startValue;
        float startA = ((startInt >> 24) & 0xff) / 255.0f;
        float startR = ((startInt >> 16) & 0xff) / 255.0f;
        float startG = ((startInt >> 8) & 0xff) / 255.0f;
        float startB = (startInt & 0xff) / 255.0f;

        int endInt = (Integer) endValue;
        float endA = ((endInt >> 24) & 0xff) / 255.0f;
        float endR = ((endInt >> 16) & 0xff) / 255.0f;
        float endG = ((endInt >> 8) & 0xff) / 255.0f;
        float endB = (endInt & 0xff) / 255.0f;

        // convert from sRGB to linear
        startR = (float) Math.pow(startR, 2.2);
        startG = (float) Math.pow(startG, 2.2);
        startB = (float) Math.pow(startB, 2.2);

        endR = (float) Math.pow(endR, 2.2);
        endG = (float) Math.pow(endG, 2.2);
        endB = (float) Math.pow(endB, 2.2);

        // compute the interpolated color in linear space
        float a = startA + fraction * (endA - startA);
        float r = startR + fraction * (endR - startR);
        float g = startG + fraction * (endG - startG);
        float b = startB + fraction * (endB - startB);

        // convert back to sRGB in the [0..255] range
        a = a * 255.0f;
        r = (float) Math.pow(r, 1.0 / 2.2) * 255.0f;
        g = (float) Math.pow(g, 1.0 / 2.2) * 255.0f;
        b = (float) Math.pow(b, 1.0 / 2.2) * 255.0f;

        return Math.round(a) << 24 | Math.round(r) << 16 | Math.round(g) << 8 | Math.round(b);
    }
}
2. 添加ItemView
private void addItem(List<BusinessTag> list) {
        for (int i = 0; i < list.size(); i++) {
            BusinessTag businessTag = list.get(i);
            BusinessTabItemView myLinearLayout = new BusinessTabItemView(getContext());
            myLinearLayout.setGravity(Gravity.CENTER);
            myLinearLayout.setData(businessTag, i == 0 ? true : false);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            myLinearLayout.setLayoutParams(layoutParams);
            addTab(i, myLinearLayout);
        }
    }
/**
     * 添加到容器
     * @param position
     * @param tab
     */
    private void addTab(final int position, View tab) {
        tab.setFocusable(true);
        tab.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                pager.setCurrentItem(position);
            }
        });
        tab.setPadding(tabPadding, 0, tabPadding, 0);
        tabsContainer.addView(tab, position, shouldExpand ? expandedTabLayoutParams : defaultTabLayoutParams);
    }
上面是項(xiàng)目中需要的效果捎谨,如果只是展示一個(gè)TextView或者是一個(gè)Icon加TextView的話(huà)請(qǐng)看下面:
     /**
     * 帶icon的Item
     * @param position 
     * @param title
     * @param drawableId
     */
private void addTextTab(final int position, String title, int drawableId) {
        TextView tab = new TextView(getContext());
        tab.setText(title);
        tab.setGravity(Gravity.CENTER);
        tab.setSingleLine();
        Drawable drawable = getContext().getDrawable(drawableId);
        if (drawable != null) {
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getIntrinsicHeight());
            tab.setCompoundDrawables(drawable, null, null, null);
            tab.setCompoundDrawablePadding(20);
        }
        addTab(position, tab);
    }
private void addTextTab(final int position, String title) {

        TextView tab = new TextView(getContext());
        tab.setText(title);
        tab.setGravity(Gravity.CENTER);
        tab.setSingleLine();
        tab.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
        addTab(position, tab);
    }
3.繪制藍(lán)色背景
@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (isInEditMode() || tabCount == 0) {
            return;
        }

        final int height = getHeight();

        // default: line below current tab
        View currentTab = tabsContainer.getChildAt(currentPosition);
        float lineLeft = currentTab.getLeft();
        float lineRight = currentTab.getRight();
        //設(shè)置為時(shí)權(quán)重  要減去item本身和兩邊padding再除以2得到左右編劇偏移量
        int side = (currentTab.getWidth() - Util.dp2px(getContext(), 75) - tabPadding * 2) / 2;
        //最小邊距
        int leastSide = Util.dp2px(getContext(), 5);
        //如果小于最小邊距就等于最小邊距
        if (side < leastSide) {
            side = leastSide;
        }
        // if there is an offset, start interpolating left and right coordinates between current and next tab
        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.drawRoundRect(lineLeft + side, bgTopBottomMargin, lineRight - side, height - bgTopBottomMargin, radius, radius, dividerPaint);
        //canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint);
    }
  • canvas.drawRoundRect(lineLeft , top, lineRight , height , radius, radius, dividerPaint);
    top:繪制的高度起始點(diǎn)
    left:繪制寬的結(jié)束點(diǎn)
    bottom:繪制的高度結(jié)束點(diǎn)
    rx:x軸弧度
    ry:y軸弧度
    paint:畫(huà)筆
    int side = (currentTab.getWidth() - Util.dp2px(getContext(), 75) - tabPadding * 2) / 2;
    side item寬減(item里text加圖片的寬)減兩邊padding再除以二得到左右邊距移量民效,目的是讓左右邊距加大,藍(lán)色背景繪制窄一點(diǎn)涛救,充滿(mǎn)的話(huà)效果不好畏邢。
4. 計(jì)算滑動(dòng)距離并在ViewPager的滑動(dòng)事件調(diào)用
 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);
        }

    }
private class PageListener implements ViewPager.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);
            }
            //控制文字顏色
            if (positionOffset > 0) {
                BusinessTabItemView left = (BusinessTabItemView) tabsContainer.getChildAt(position);
                BusinessTabItemView right = (BusinessTabItemView) tabsContainer.getChildAt(position + 1);
                left.setProgress((1 - positionOffset));
                right.setProgress(positionOffset);
            }
        }

        @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);
            }
            for (int i = 0; i < tagList.size(); i++) {
                BusinessTag businessTag = tagList.get(i);
                BusinessTabItemView childAt = (BusinessTabItemView) tabsContainer.getChildAt(i);
                childAt.setChoice(businessTag, i == position ? true : false);
            }
        }
    }
  • onPageSelected()里的代碼可以不用
SlidingTabView全部代碼
public class SlidingTabView extends HorizontalScrollView {
    /**
     * Item之間的間距
     */
    private int margins;

    public interface IconTabProvider {
        public int getPageIconResId(int position);
    }

    // @formatter:off
    private static final int[] ATTRS = new int[]{android.R.attr.textSize, android.R.attr.textColor};
    // @formatter:on

    private LinearLayout.LayoutParams defaultTabLayoutParams;
    private LinearLayout.LayoutParams expandedTabLayoutParams;

    private final PageListener pageListener = new PageListener();
    public ViewPager.OnPageChangeListener delegatePageListener;

    private LinearLayout tabsContainer;
    private ViewPager pager;

    private int tabCount;

    private int currentPosition = 0;
    private float currentPositionOffset = 0f;

    private Paint dividerPaint;

    private int dividerColor = 0x1A000000;

    private boolean shouldExpand = false;

    private int scrollOffset = 52;
    private int radius = Util.dp2px(getContext(), 10);
    private int tabPadding = 24;
    private int dividerWidth = 1;
    private int lastScrollX = 0;

    private int bgTopBottomMargin = 10;

    private Locale locale;
    /**
     * 業(yè)務(wù)數(shù)據(jù)
     */
    private List<BusinessTag> tagList;

    public SlidingTabView(Context context) {
        this(context, null);
    }

    public SlidingTabView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlidingTabView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        setFillViewport(true);
        setWillNotDraw(false);

        tabsContainer = new LinearLayout(context);
        tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        tabsContainer.setLayoutParams(layoutParams);

        addView(tabsContainer);

        DisplayMetrics dm = getResources().getDisplayMetrics();

        scrollOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm);
        tabPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm);
        dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm);
        bgTopBottomMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, bgTopBottomMargin, dm);
        // get system attrs (android:textSize and android:textColor)
        TypedArray a = context.obtainStyledAttributes(attrs, ATTRS);
        a.recycle();
        // get custom attrs
        a = context.obtainStyledAttributes(attrs, R.styleable.BusinessSlidingTabView);
        //是否需要鋪滿(mǎn) 必須為T(mén)rue
        shouldExpand = a.getBoolean(R.styleable.BusinessSlidingTabView_pstsShouldExpand, shouldExpand);
        scrollOffset = a.getDimensionPixelSize(R.styleable.BusinessSlidingTabView_pstsScrollOffset, scrollOffset);
        //弧度
        radius = a.getDimensionPixelSize(R.styleable.BusinessSlidingTabView_pstsRadius, radius);
        //背景色
        dividerColor = a.getColor(R.styleable.BusinessSlidingTabView_pstsDividerColor, dividerColor);
//        padding
        tabPadding = a.getDimensionPixelSize(R.styleable.BusinessSlidingTabView_pstsTabPaddingLeftRight, tabPadding);
        a.recycle();

        dividerPaint = new Paint();
        dividerPaint.setAntiAlias(true);
        dividerPaint.setStrokeWidth(dividerWidth);
        dividerPaint.setColor(dividerColor);

        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;
        }
    }

    /**
     * 與ViewPager關(guān)聯(lián)
     * @param pager
     * @param list
     */
    public void setViewPager(ViewPager pager, List<BusinessTag> list) {
        this.pager = pager;
        tagList = list;
        if (pager.getAdapter() == null) {
            throw new IllegalStateException("ViewPager does not have adapter instance.");
        }

        pager.addOnPageChangeListener(pageListener);

        notifyDataSetChanged(list);
    }

    public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
        this.delegatePageListener = listener;
    }

    /**
     * 添加刷新
     * @param list
     */
    public void notifyDataSetChanged(List<BusinessTag> list) {
        tabsContainer.removeAllViews();
        tabCount = list.size();
        addItem(list);
        //updateTabStyles();
        getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @SuppressWarnings("deprecation")
            @SuppressLint("NewApi")
            @Override
            public void onGlobalLayout() {

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }

                currentPosition = pager.getCurrentItem();
                scrollToChild(currentPosition, 0);
            }
        });
    }

    private void addTextTab(final int position, String title, int drawableId) {

        TextView tab = new TextView(getContext());
        tab.setText(title);
        tab.setGravity(Gravity.CENTER);
        tab.setSingleLine();
        Drawable drawable = getContext().getDrawable(drawableId);
        if (drawable != null) {
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getIntrinsicHeight());
            tab.setCompoundDrawables(drawable, null, null, null);
            tab.setCompoundDrawablePadding(20);
        }
        addTab(position, tab);
    }

    /**
     * 添加Item
     * @param list
     */
    private void addItem(List<BusinessTag> list) {
        for (int i = 0; i < list.size(); i++) {
            BusinessTag businessTag = list.get(i);
            BusinessTabItemView myLinearLayout = new BusinessTabItemView(getContext());
            myLinearLayout.setGravity(Gravity.CENTER);
            myLinearLayout.setData(businessTag, i == 0 ? true : false);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//            layoutParams.setMargins(100,0,100,0);
            myLinearLayout.setLayoutParams(layoutParams);
            addTab(i, myLinearLayout);
        }
    }

    private void addTextTab(final int position, String title) {

        TextView tab = new TextView(getContext());
        tab.setText(title);
        tab.setGravity(Gravity.CENTER);
        tab.setSingleLine();
        tab.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
        addTab(position, tab);
    }

    /**
     * 添加到容器
     * @param position
     * @param tab
     */
    private void addTab(final int position, View tab) {
        tab.setFocusable(true);
        tab.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                pager.setCurrentItem(position);
            }
        });
        tab.setPadding(tabPadding, 0, tabPadding, 0);
        tabsContainer.addView(tab, position, shouldExpand ? expandedTabLayoutParams : defaultTabLayoutParams);
    }

    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);
        }

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (isInEditMode() || tabCount == 0) {
            return;
        }

        final int height = getHeight();

        // default: line below current tab
        View currentTab = tabsContainer.getChildAt(currentPosition);
        float lineLeft = currentTab.getLeft();
        float lineRight = currentTab.getRight();
        //設(shè)置為時(shí)權(quán)重  要減去item本身和兩邊padding再除以2得到左右編劇偏移量
        int side = (currentTab.getWidth() - Util.dp2px(getContext(), 75) - tabPadding * 2) / 2;
        //最小邊距
        int leastSide = Util.dp2px(getContext(), 5);
        //如果小于最小邊距就等于最小邊距
        if (side < leastSide) {
            side = leastSide;
        }
        // if there is an offset, start interpolating left and right coordinates between current and next tab
        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);
            Log.e("zby", "左:"+lineLeft+"----"+"右:"+lineRight);
        }
        //繪制背景
        canvas.drawRoundRect(lineLeft , 0, lineRight , height , radius, radius, dividerPaint);
        //canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint);
    }

    private class PageListener implements ViewPager.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);
            }
            //控制文字顏色
            if (positionOffset > 0) {
                BusinessTabItemView left = (BusinessTabItemView) tabsContainer.getChildAt(position);
                BusinessTabItemView right = (BusinessTabItemView) tabsContainer.getChildAt(position + 1);
                left.setProgress((1 - positionOffset));
                right.setProgress(positionOffset);
            }
        }

        @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);
            }
            for (int i = 0; i < tagList.size(); i++) {
                BusinessTag businessTag = tagList.get(i);
                BusinessTabItemView childAt = (BusinessTabItemView) tabsContainer.getChildAt(i);
                childAt.setChoice(businessTag, i == position ? true : false);
            }
        }
    }
    public int setChoice(String code){
        int choice = 0;
        if (tagList == null || tagList.size() <= 0) {
            choice = 0;
        } else {
            try {
                choice = tagList.indexOf(new BusinessTag(code));
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (choice < 0) {
                choice = 0;
            }
        }
        return choice;
    }
    public void setDividerColor(int dividerColor) {
        this.dividerColor = dividerColor;
        invalidate();
    }

    public void setDividerColorResource(int resId) {
        this.dividerColor = getResources().getColor(resId);
        invalidate();
    }

    public int getDividerColor() {
        return dividerColor;
    }

    public void setScrollOffset(int scrollOffsetPx) {
        this.scrollOffset = scrollOffsetPx;
        invalidate();
    }

    public int getScrollOffset() {
        return scrollOffset;
    }

    public void setShouldExpand(boolean shouldExpand) {
        this.shouldExpand = shouldExpand;
        requestLayout();
    }

    public boolean getShouldExpand() {
        return shouldExpand;
    }

    public int getTabPaddingLeftRight() {
        return tabPadding;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState savedState = (SavedState) state;
        super.onRestoreInstanceState(savedState.getSuperState());
        currentPosition = savedState.currentPosition;
        requestLayout();
    }

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState savedState = new SavedState(superState);
        savedState.currentPosition = currentPosition;
        return savedState;
    }

    static class SavedState extends BaseSavedState {
        int currentPosition;

        public SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            currentPosition = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
            dest.writeInt(currentPosition);
        }

        public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }

}
XML布局

pstsDividerColor:背景色
pstsRadius:背景弧度
pstsTabPaddingLeftRight:左右邊距
pstsShouldExpand:是否設(shè)權(quán)重 (建議必須設(shè))

 <cn.nova.phone.common.view.BusinessSlidingTabView
            android:id="@+id/businessTagView"
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:layout_gravity="center"
            android:background="@color/white"
            app:pstsDividerColor="@color/blue"
            app:pstsRadius="15dp"
            app:pstsShouldExpand="true"
            app:pstsTabPaddingLeftRight="5dp" />
調(diào)用一行代碼搞定
 businessTagView.setViewPager(vp_main,tagList);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市检吆,隨后出現(xiàn)的幾起案子舒萎,更是在濱河造成了極大的恐慌,老刑警劉巖蹭沛,帶你破解...
    沈念sama閱讀 217,542評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件臂寝,死亡現(xiàn)場(chǎng)離奇詭異章鲤,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)咆贬,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén)败徊,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人掏缎,你說(shuō)我怎么就攤上這事皱蹦。” “怎么了眷蜈?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,912評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵根欧,是天一觀(guān)的道長(zhǎng)。 經(jīng)常有香客問(wèn)我端蛆,道長(zhǎng)凤粗,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,449評(píng)論 1 293
  • 正文 為了忘掉前任今豆,我火速辦了婚禮嫌拣,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘呆躲。我一直安慰自己异逐,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,500評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布插掂。 她就那樣靜靜地躺著灰瞻,像睡著了一般。 火紅的嫁衣襯著肌膚如雪辅甥。 梳的紋絲不亂的頭發(fā)上酝润,一...
    開(kāi)封第一講書(shū)人閱讀 51,370評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音璃弄,去河邊找鬼要销。 笑死,一個(gè)胖子當(dāng)著我的面吹牛夏块,可吹牛的內(nèi)容都是我干的疏咐。 我是一名探鬼主播,決...
    沈念sama閱讀 40,193評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼脐供,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼浑塞!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起政己,我...
    開(kāi)封第一講書(shū)人閱讀 39,074評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤酌壕,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體仅孩,經(jīng)...
    沈念sama閱讀 45,505評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡托猩,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,722評(píng)論 3 335
  • 正文 我和宋清朗相戀三年印蓖,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了辽慕。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,841評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡赦肃,死狀恐怖溅蛉,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情他宛,我是刑警寧澤船侧,帶...
    沈念sama閱讀 35,569評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站厅各,受9級(jí)特大地震影響镜撩,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜队塘,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,168評(píng)論 3 328
  • 文/蒙蒙 一袁梗、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧憔古,春花似錦遮怜、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,783評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至焰情,卻和暖如春陌凳,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背内舟。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,918評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工冯遂, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人谒获。 一個(gè)月前我還...
    沈念sama閱讀 47,962評(píng)論 2 370
  • 正文 我出身青樓蛤肌,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親批狱。 傳聞我的和親對(duì)象是個(gè)殘疾皇子裸准,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,781評(píng)論 2 354