实现ViewPager导航条,为了方便,使用这个banner库https://github.com/liugongce/banner进行测试,编写如下代码实现导航条功能
public class BannerBar extends View {
private static final String DEF_BAR_COLOR = "#FF719B";
private int barWidth;
private int barHeight;
private int barColor;
private int curLeft;
private int curOffset;
private Paint mPaint;
private PagerAdapter pagerAdapter;
private ViewPager.OnPageChangeListener mPageChangeListener;
public BannerBar(Context context) {
this(context, null);
}
public BannerBar(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BannerBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
barColor = Color.parseColor(DEF_BAR_COLOR);
barHeight = dp2px(context, 3);
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (pagerAdapter != null) {
int width = getMeasuredWidth();
int count = pagerAdapter.getCount();
barWidth = width / count;
}
setMeasuredDimension(getMeasuredWidth(), barHeight);
}
public void stepWithViewPager(final ViewPager viewPager) {
pagerAdapter = viewPager.getAdapter();
int width = getMeasuredWidth();
int count = pagerAdapter.getCount();
barWidth = width / count;
curOffset = 0;
curLeft = 0;
invalidate();
if (mPageChangeListener != null) {
viewPager.removeOnPageChangeListener(mPageChangeListener);
}
mPageChangeListener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int curPage = viewPager.getCurrentItem();
if (curPage == position) { //往右滑
curOffset = (int) (positionOffset * barWidth);
} else if (curPage > position) { //往左滑
curOffset = -(int) ((1 - positionOffset) * barWidth);
}
invalidate();
}
@Override
public void onPageSelected(int position) {
curOffset = 0;
curLeft = position * barWidth;
invalidate();
}
@Override
public void onPageScrollStateChanged(int state) {
if (state == 1) {
curOffset = 0;
}
}
};
viewPager.addOnPageChangeListener(mPageChangeListener);
}
@Override
protected void onDraw(Canvas canvas) {
mPaint.setColor(barColor);
int left = curLeft + curOffset;
int top = 0;
int right = left + barWidth;
int bottom = barHeight;
canvas.drawRect(left, top, right, bottom, mPaint);
}
private static int dp2px(Context context, float dpValue) {
final float density = context.getResources().getDisplayMetrics().density;
return Math.round(dpValue * density);
}
}
思路很简单,onDraw方法中画个矩形,决定矩形位置的几个变量与ViewPager关联即可。矩形的相关配置目前没有提供对外接口,可以按需要修改代码。
使用方法:
BannerBar bannerBar = findViewById(R.id.banner_bar);
bannerBar.stepWithViewPager(viewPager);