Search code examples
androidprogress-barandroid-custom-view

android progress bar with text inside in center render issue


I've created a custom progress bar with text inside it. solution was working properly but now text gets created to top of progress bar instead of center. When Activity pauses and resumes. progress bar renders again and then text appears at the center. please see my code below.

public class TextProgressBar extends ProgressBar {
private String text;
private Paint textPaint;

public TextProgressBar(Context context) {
    super(context);
    text = "";
    textPaint = new Paint();
    textPaint.setColor(Color.BLACK);
    //textPaint.setShadowLayer(1,1,1,Color.WHITE);
    textPaint.setTypeface(Typeface.create(Typeface.DEFAULT,Typeface.BOLD));
}

public TextProgressBar(Context context, AttributeSet attrs) {
    super(context, attrs);
    text = "";
    textPaint = new Paint();
    textPaint.setColor(Color.BLACK);
    textPaint.setTypeface(Typeface.create(Typeface.DEFAULT,Typeface.BOLD));
}

public TextProgressBar(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    text = "";
    textPaint = new Paint();
    textPaint.setColor(Color.BLACK);
    textPaint.setTypeface(Typeface.create(Typeface.DEFAULT,Typeface.BOLD));
}

@Override
protected synchronized void onDraw(Canvas canvas) {
    // First draw the regular progress bar, then custom draw our text
    super.onDraw(canvas);
    Rect bounds = new Rect();
    textPaint.getTextBounds(text, 0, text.length(), bounds);
    textPaint.setTextSize(getHeight() * 0.8f);
    int x = (getWidth()/2) - bounds.centerX();
    int y = (getHeight()/2) - bounds.centerY();
    canvas.drawText(text, x, y, textPaint);

}

public synchronized void setText(String text) {
    this.text = text;
    drawableStateChanged();
}

public synchronized void setPercentText(int percentText){
    this.text = percentText + " %";
}

public void setTextColor(int color) {
    textPaint.setColor(color);
    drawableStateChanged();
}
}

How it appears when loaded

enter image description here

How it appears after recreate

normal Image


Solution

  • Try requestLayout() just after inflation. It will force measure() again for View. See the life cycle of View.

    enter image description here