前言:
这个是与上篇 ViewPager指示器(三角形) 一个版本做的效果主要的滑动原理大致相同,话不多说先看效果。
- 这个用TabLayout是无法实现的只能自己写自定义的,当时在网上找了很多都不是自己想要的,后再在github上找到一个跟我要的很相近的就拿过来改了改。
实现思路
- 我是用的HorizontalScrollView,在HorizontalScrollView添加一个LinearLayout,文字和动态图我写了一个itemView,再把itemView Add到LinearLayout里。
1.先把ItemView写好。
2.ItemView添加到LinearLayout容器里。
3.获取当Item的宽高,绘制蓝色背景。
4.计算滑动距离并在ViewPager的滑动事件调用。
实现步骤 (主要为核心代码,全部代码在最后面)
1. ItemView里多了个颜色渐变的方法,没有什么需要说的直接贴代码了。
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);
}
/**
* 设置数据
* @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));
}
}
/**
* 设置选中
* @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));
}
}
/**
* 通过code获取GifIcon的id
*
* @param code
* @return
*/
private int getGifIconID(String code) {
int icon = R.drawable.business_tag_qcp;
switch (code) {
case GlobalUrlConfig.businesscode_qcp:
//汽车票
icon = R.drawable.gif_business_tag_qcp;
break;
case GlobalUrlConfig.businesscode_zx:
//专线
icon = R.drawable.gif_business_tag_dzzx;
break;
case GlobalUrlConfig.businesscode_hcp:
//火车票
icon = R.drawable.gif_business_tag_hcp;
break;
default:
break;
}
return icon;
}
/**
* 设置字体渐变
* @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 进度
* @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);
}
上面是项目中需要的效果,如果只是展示一个TextView或者是一个Icon加TextView的话请看下面:
/**
* 带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.绘制蓝色背景
@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();
//设置为时权重 要减去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:绘制的高度起始点
left:绘制宽的结束点
bottom:绘制的高度结束点
rx:x轴弧度
ry:y轴弧度
paint:画笔
int side = (currentTab.getWidth() - Util.dp2px(getContext(), 75) - tabPadding * 2) / 2;
side item宽减(item里text加图片的宽)减两边padding再除以二得到左右边距移量,目的是让左右边距加大,蓝色背景绘制窄一点,充满的话效果不好。
4. 计算滑动距离并在ViewPager的滑动事件调用
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;
/**
* 业务数据
*/
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);
//是否需要铺满 必须为True
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关联
* @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();
//设置为时权重 要减去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:是否设权重 (建议必须设)
<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" />
调用一行代码搞定
businessTagView.setViewPager(vp_main,tagList);