How add TextView in middle of SeekBar thumb? [duplicate]

If I understand your question right, you want to place text inside of the thumb on a seekbar like so:

enter image description here

The Android Seekbar doesn’t expose any public or protected methods that allows you to set a text in the thumb. So you can’t implement a solution with the Android SeekBar as is.

As a solution, you can write your own CustomSeekBar.

The Android SeekBar extends AbsSeekBar. It’s in AbsSeekBar that the thumb’s position is set, like so:

 private void setThumbPos(int w, Drawable thumb, float scale, int gap) {
    int available = w - mPaddingLeft - mPaddingRight;
    int thumbWidth = thumb.getIntrinsicWidth();
    int thumbHeight = thumb.getIntrinsicHeight();
    available -= thumbWidth;

    // The extra space for the thumb to move on the track
    available += mThumbOffset * 2;

    //Determine horizontal position
    int thumbPos = (int) (scale * available);

    //Determine vertical position
    int topBound, bottomBound;
    if (gap == Integer.MIN_VALUE) {
        Rect oldBounds = thumb.getBounds();
        topBound = oldBounds.top;
        bottomBound = oldBounds.bottom;
    } else {
        topBound = gap;
        bottomBound = gap + thumbHeight;
    }

    //Set the thumbs position
    thumb.setBounds(thumbPos, topBound, thumbPos + thumbWidth, bottomBound);
}

and in AbsSeekBar’s onDraw() method, the thumb is drawn:

mThumb.draw(canvas);

To implement your own SeekBar, you first create a CustomSeekBar class that extends AbsSeekBar. You then override AbsSeekBar’s setThumPos() method in your CustomSeekBar class, and there set the position of your own custom thumb.

Your custom thumb would be a View or ViewGroup,e.g. LinearLayout, with a background drawable and a TextView for the percentage progress text.

You then have to decide how to write the percentage progress to the custom thumb. You could write the percentage progress text on the thumb in a new writeTextOnThumb method() called inside setThumbPos(), or you could expose it as a public method in your CustomSeekBar’s API.

Leave a Comment