public class TextProgressView extends AppCompatSeekBar {
private Paint mPaint;
private Rect mRect;
private String mText;
public TextProgressView (@NonNull Context context) {
this(context, null);
}
public TextProgressView (@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public TextProgressView (@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
setClickable(false);
setFocusable(false);
setFocusableInTouchMode(false);
setMax(100);
setOnTouchListener(new OnTouchListener() {
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
}
private void initView() {
mPaint = new Paint();
mPaint.setColor(Color.WHITE);
mPaint.setTextSize(PixelFormat.dip2px(getContext(), 12));
mPaint.setAntiAlias(true);
mRect = new Rect();
mText = "";
}
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (TextUtils.isEmpty(this.mText)) return;
mPaint.getTextBounds(this.mText, 0, this.mText.length(), mRect);
float progressRatio = (float) getProgress() / getMax();
canvas.drawText(this.mText, getWidth() * progressRatio - mRect.width()/2f, (getHeight() / 2f) - mRect.centerY(), mPaint);
}
public void setKaihuProgress(int progress) {
this.mText = progress + "%";
setProgress(progress);
}
}
网友评论