Thursday 24 May 2012

Custom progressbar in android with text - part 3


Hello all......

I have posted two posts on how to customize a progressbar in android.

1. <a href="http://www.coderzheaven.com/2012/03/29/custom-indeterminate-progressbar-for-android/" target="_blank">Custom Indeterminate progressBar for android?</a>
2. <a href="http://www.coderzheaven.com/2012/05/12/build-custom-progressbar-android-part-2/" target="_blank">How to build a custom progressBar in android- Part 2?</a>

Here is another one with update text on top of the progressbar.

Here is how we start.

After creating a fresh project create a new java file and name it "TextProgressBar.java".

Now copy this code to the above file.
This file extends the progressbar to add additional functionality.

[java]
package com.coderzheaven.pack;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.ProgressBar;

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

public TextProgressBar(Context context) {
super(context);
text = "0/100";
textPaint = new Paint();
textPaint.setColor(Color.BLACK);
}

public TextProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
text = "0/100";
textPaint = new Paint();
textPaint.setColor(Color.BLACK);
}

public TextProgressBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
text = "0/100";
textPaint = new Paint();
textPaint.setColor(Color.BLACK);
}

@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
Rect bounds = new Rect();
textPaint.getTextBounds(text, 0, text.length(), bounds);
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 void setTextColor(int color) {
textPaint.setColor(color);
drawableStateChanged();
}
}
[/java]

OK the progressbar class is now complete.

No comments:

Post a Comment