可以设置颜色,并且底部横线与字体宽度一致的PagerSlidingTabStrip

来源:互联网 发布:linux系统密码修改 编辑:程序博客网 时间:2024/06/06 19:08

这里写图片描述

PagerSlidingTabStrip可以设置字体颜色,并且底部横线与字体宽度一致

public class PagerSlidingTabStrip  extends HorizontalScrollView{    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 int selectedPosition = 0;    private float currentPositionOffset = 0f;    private Paint rectPaint;    private Paint dividerPaint;    private int indicatorColor = 0xFF666666;    private int underlineColor = 0x1A000000;    private int dividerColor = 0x1A000000;    private boolean shouldExpand = false;    private boolean textAllCaps = true;    private int scrollOffset = 52;    private int indicatorHeight = 8;    private int underlineHeight = 2;    private int dividerPadding = 12;    private int tabPadding = 24;    private int dividerWidth = 1;    private int tabTextSize = 12;    private int tabTextColor = 0xFF666666;    private int selectedTabTextColor = 0xFF666666;    private Typeface tabTypeface = null;    private int tabTypefaceStyle = Typeface.NORMAL;    private int lastScrollX = 0;    private int tabBackgroundResId = R.drawable.background_tab;    private Locale locale;    public PagerSlidingTabStrip(Context context) {        this(context, null);    }    public PagerSlidingTabStrip(Context context, AttributeSet attrs) {        this(context, attrs, 0);    }    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(Paint.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;        }    }    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(ViewPager.OnPageChangeListener listener) {        this.delegatePageListener = listener;    }    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());            }        }        updateTabStyles();        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {            @Override            public void onGlobalLayout() {                getViewTreeObserver().removeGlobalOnLayoutListener(this);                currentPosition = pager.getCurrentItem();                scrollToChild(currentPosition, 0);            }        });    }    private void addTextTab(final int position, String title) {        TextView tab = new TextView(getContext());        tab.setText(title);        tab.setGravity(Gravity.CENTER);        tab.setSingleLine();        addTab(position, tab);    }    private void addIconTab(final int position, int resId) {        ImageButton tab = new ImageButton(getContext());        tab.setImageResource(resId);        addTab(position, 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 updateTabStyles() {        for (int i = 0; i < tabCount; i++) {            View v = tabsContainer.getChildAt(i);            v.setBackgroundResource(tabBackgroundResId);            if (v instanceof TextView) {                TextView tab = (TextView) v;                tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize);                tab.setTypeface(tabTypeface, tabTypefaceStyle);                tab.setTextColor(tabTextColor);                // setAllCaps() is only available from API 14, so the upper case is made manually if we are on a                // pre-ICS-build                if (textAllCaps) {                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {                        tab.setAllCaps(true);                    } else {                        tab.setText(tab.getText().toString().toUpperCase(locale));                    }                }                if (i == selectedPosition) {                    tab.setTextColor(selectedTabTextColor);                }            }        }    }    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();        // draw underline        rectPaint.setColor(underlineColor);        canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint);        // draw indicator line        rectPaint.setColor(indicatorColor);        // default: line below current tab        View currentTab = tabsContainer.getChildAt(currentPosition);        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) {            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);        }        //通过处理tabPadding,设置底部横线与文字宽度一致,        canvas.drawRect(lineLeft+tabPadding, height - indicatorHeight, lineRight-tabPadding, height, rectPaint);        //默认设置,底部横线填满宽度       // canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint);        // draw divider        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);        }    }    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);            }        }        @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) {            selectedPosition = position;            updateTabStyles();            if (delegatePageListener != null) {                delegatePageListener.onPageSelected(position);            }        }    }    public void setIndicatorColor(int indicatorColor) {        this.indicatorColor = indicatorColor;        invalidate();    }    public void setIndicatorColorResource(int resId) {        this.indicatorColor = getResources().getColor(resId);        invalidate();    }    public int getIndicatorColor() {        return this.indicatorColor;    }    public void setIndicatorHeight(int indicatorLineHeightPx) {        this.indicatorHeight = indicatorLineHeightPx;        invalidate();    }    public int getIndicatorHeight() {        return indicatorHeight;    }    public void setUnderlineColor(int underlineColor) {        this.underlineColor = underlineColor;        invalidate();    }    public void setUnderlineColorResource(int resId) {        this.underlineColor = getResources().getColor(resId);        invalidate();    }    public int getUnderlineColor() {        return underlineColor;    }    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 setUnderlineHeight(int underlineHeightPx) {        this.underlineHeight = underlineHeightPx;        invalidate();    }    public int getUnderlineHeight() {        return underlineHeight;    }    public void setDividerPadding(int dividerPaddingPx) {        this.dividerPadding = dividerPaddingPx;        invalidate();    }    public int getDividerPadding() {        return dividerPadding;    }    public void setScrollOffset(int scrollOffsetPx) {        this.scrollOffset = scrollOffsetPx;        invalidate();    }    public int getScrollOffset() {        return scrollOffset;    }    public void setShouldExpand(boolean shouldExpand) {        this.shouldExpand = shouldExpand;        notifyDataSetChanged();    }    public boolean getShouldExpand() {        return shouldExpand;    }    public boolean isTextAllCaps() {        return textAllCaps;    }    public void setAllCaps(boolean textAllCaps) {        this.textAllCaps = textAllCaps;    }    public void setTextSize(int textSizePx) {        this.tabTextSize = textSizePx;        updateTabStyles();    }    public int getTextSize() {        return tabTextSize;    }    public void setTextColor(int textColor) {        this.tabTextColor = textColor;        updateTabStyles();    }    public void setTextColorResource(int resId) {        this.tabTextColor = getResources().getColor(resId);        updateTabStyles();    }    public int getTextColor() {        return tabTextColor;    }    public void setSelectedTextColor(int textColor) {        this.selectedTabTextColor = textColor;        updateTabStyles();    }    public void setSelectedTextColorResource(int resId) {        this.selectedTabTextColor = getResources().getColor(resId);        updateTabStyles();    }    public int getSelectedTextColor() {        return selectedTabTextColor;    }    public void setTypeface(Typeface typeface, int style) {        this.tabTypeface = typeface;        this.tabTypefaceStyle = style;        updateTabStyles();    }    public void setTabBackground(int resId) {        this.tabBackgroundResId = resId;        updateTabStyles();    }    public int getTabBackground() {        return tabBackgroundResId;    }    public void setTabPaddingLeftRight(int paddingPx) {        this.tabPadding = paddingPx;        updateTabStyles();    }    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 Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {            @Override            public SavedState createFromParcel(Parcel in) {                return new SavedState(in);            }            @Override            public SavedState[] newArray(int size) {                return new SavedState[size];            }        };    }}
private void setPagerSlidingTabStrip()    {        tabs.setIndicatorColor(R.color.color_green_34cb80);        // 设置Tab是自动填充满屏幕的        tabs.setShouldExpand(true);        // 设置Tab的分割线是透明的        tabs.setDividerColor(Color.TRANSPARENT);        // 设置Tab底部线的高度        tabs.setUnderlineHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, dm));        // 设置Tab Indicator的高度        tabs.setIndicatorHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, dm));        tabs.setDividerPadding((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, dm));        // 设置Tab标题文字的大小        tabs.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 15, dm));        // 设置Tab标题默认的颜色        tabs.setTextColor(getResources().getColor(R.color.get_record_text_unselected_color));        // 设置选中Tab标题的颜色        tabs.setSelectedTextColor(getResources().getColor(R.color.get_record_text_selected_color));        // 设置Tab底部线的颜色        tabs.setUnderlineColor(Color.TRANSPARENT);        // 设置Tab Indicator的颜色        tabs.setIndicatorColor(getResources().getColor(R.color.get_record_line_selected_color));    }    class MyPagerAdapter extends FragmentPagerAdapter    {        public MyPagerAdapter(FragmentManager fm)        {            super(fm);        }        @Override        public Fragment getItem(int position)        {            return HealthEducationFragment.newInstance(articleBeanArrayList.get(position).getId());        }        @Override        public int getCount()        {            return articleBeanArrayList.size();        }        @Override        public int getItemPosition(Object object)        {            return PagerAdapter.POSITION_NONE;        }        @Override        public CharSequence getPageTitle(int position)        {            SpannableStringBuilder ssb = new SpannableStringBuilder(" " + articleBeanArrayList.get(position).getName()); // space added before text for            ForegroundColorSpan fcs = new ForegroundColorSpan(Color.parseColor("#34cb80"));//字体颜色设置为绿色            ssb.setSpan(fcs, 1, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//设置字体颜色            ssb.setSpan(new RelativeSizeSpan(1.2f), 1, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);            return ssb;        }    }

设置:
@Override
public int getItemPosition(Object object)
{
return PagerAdapter.POSITION_NONE;
}
是为了在viewpager中,因为下一界面有类似于新闻类的标签功能,根据选择的标签,返回本页以后,动态替换viewpager中的fragment,解决notifyDataSetChanged()不刷新的问题
参考文章如何更新及替换ViewPager中的Fragment
动态修改viewpager里面的fragment(添加和删除)

使用PagerSlidingTabStrip和ViewPager实现可左右滑动和点击效果功能

阅读全文
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 短发洗完头头发向外外怎么办 20岁掉头发厉害怎么办 20岁老掉头发怎么办 20岁有点掉头发怎么办 20岁开始掉头发怎么办 20岁掉头发严重怎么办 20岁脱发很严重怎么办 手的纹路很深怎么办 20岁白头发很多怎么办 一天掉40根头发怎么办 烫完头发掉头皮怎么办 接发遗留的胶水怎么办 头发又干又卷怎么办 每天掉很多头发怎么办掉头发 植过发15天手抓植发区了怎么办 洗头梳头老掉头发怎么办 掉头发特别特别严重怎么办 哺乳期掉头发特别严重怎么办 最近掉头发特别严重怎么办 近掉头发特别严重怎么办 50多岁脱发严重怎么办 2岁宝宝掉发严重怎么办 生孩子后掉头发严重怎么办 有16岁孩孑教吾听怎么办 生完孩子后脱发怎么办 学生掉头发很厉害怎么办 35岁开始掉头发怎么办 高三学生玩手机怎么办 高三学生不学习怎么办 17岁经常掉头发怎么办 出汗后头皮很痒怎么办 头发老是掉怎么办会不会长出来 头发痒还掉头发怎么办 7个月宝宝入睡难怎么办 45天宝宝入睡难怎么办 两岁宝宝入睡难怎么办 吃激素掉发严重怎么办 20多岁掉头发怎么办 最近头发老掉怎么办20 20多岁最近严重脱发怎么办 头痒头皮屑多掉头发怎么办