-
-
Notifications
You must be signed in to change notification settings - Fork 440
10.自定义Indicator
zhangpan edited this page Jun 26, 2022
·
5 revisions
在内置Indicator不满足需求时可以通过自定义IndicatorView实现,例子将实现一个如下图所示的IndicatorView。
Custom IndicatorView |
---|
public class FigureIndicatorView extends BaseIndicatorView {
private int radius = DpUtils.dp2px(20);
private int backgroundColor = Color.parseColor("#88FF5252");
private int textColor = Color.WHITE;
private int textSize=DpUtils.dp2px(13);
public FigureIndicatorView(Context context) {
this(context, null);
}
public FigureIndicatorView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public FigureIndicatorView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mPaint = new Paint();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(2 * radius, 2 * radius);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setColor(backgroundColor);
canvas.drawCircle(getWidth() / 2, getHeight() / 2, radius, mPaint);
mPaint.setColor(textColor);
mPaint.setTextSize(textSize);
String text = currentPosition + 1 + "/" + pageSize;
int textWidth = (int) mPaint.measureText(text);
Paint.FontMetricsInt fontMetricsInt = mPaint.getFontMetricsInt();
int baseline = (getMeasuredHeight() - fontMetricsInt.bottom + fontMetricsInt.top) / 2 - fontMetricsInt.top;
canvas.drawText(text, (getWidth() - textWidth) / 2, baseline, mPaint);
}
public void setRadius(int radius) {
this.radius = radius;
}
@Override
public void setBackgroundColor(@ColorInt int backgroundColor) {
this.backgroundColor = backgroundColor;
}
public void setTextSize(int textSize) {
this.textSize = textSize;
}
public void setTextColor(int textColor) {
this.textColor = textColor;
}
}
FigureIndicatorView indicatorView = new FigureIndicatorView(mContext);
indicatorView.setRadius(getResources().getDimensionPixelOffset(R.dimen.dp_18));
indicatorView.setTextSize(getResources().getDimensionPixelSize(R.dimen.sp_13));
indicatorView.setBackgroundColor(Color.parseColor("#aa118EEA"));
mViewPager.setAdapter(adapter)
.setIndicatorView(indicatorView)
.create(getPicList(4));