Define a custom class extending SeekBar to show the progress text on thumb of SeekBar.
public class TextThumbSeekBar extends SeekBar {
private int mThumbSize;
private TextPaint mTextPaint;
public TextThumbSeekBar(Context context) {
this(context, null);
}
public TextThumbSeekBar(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.seekBarStyle);
}
public TextThumbSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mThumbSize = getResources().getDimensionPixelSize(R.dimen.thumb_size);
mTextPaint = new TextPaint();
mTextPaint.setColor(Color.WHITE);
mTextPaint.setTextSize(getResources().getDimensionPixelSize(R.dimen.thumb_text_size));
mTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
mTextPaint.setTextAlign(Paint.Align.CENTER);
}
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
String progressText = String.valueOf(getProgress());
Rect bounds = new Rect();
mTextPaint.getTextBounds(progressText, 0, progressText.length(), bounds);
int leftPadding = getPaddingLeft() - getThumbOffset();
int rightPadding = getPaddingRight() - getThumbOffset();
int width = getWidth() - leftPadding - rightPadding;
float progressRatio = (float) getProgress() / getMax();
float thumbOffset = mThumbSize * (.5f - progressRatio);
float thumbX = progressRatio * width + leftPadding + thumbOffset;
float thumbY = getHeight() / 2f + bounds.height() / 2f;
canvas.drawText(progressText, thumbX, thumbY, mTextPaint);
}
}
Use TextThumbSeekBar in your layout xml as following.
<com.yqritc.sample.TextThumbSeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="10"
android:progress="5"
android:thumb="@drawable/shape_seek_bar_text_thumb"
android:thumbOffset="4dp"/>
Define custom thumb drawable as you need like the following.
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/primary_color"/>
<size
android:width="@dimen/thumb_size"
android:height="@dimen/thumb_size"/>
</shape>
If you use image drawable as the thumb instead of xml shape drawable, set the following attribute if the background of your drawable is transparent.
android:splitTrack="false"
DONE.
Avoid object allocation in onDrawer/Layout warning...