1590738775810659.gif
實現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);