Android自定义进度条-带文本(文字进度)的水平进度条(ProgressBar)

水平进度条,显示进度的文本随着进度而移动。

效果如下,截的静态图。

Android自定义进度条-带文本(文字进度)的水平进度条(ProgressBar)

Android自定义进度条-带文本(文字进度)的水平进度条(ProgressBar)

Android自定义进度条-带文本(文字进度)的水平进度条(ProgressBar)

代码如下 TextProgressBar.java


public class TextProgressBar extends ProgressBar {

    private Paint mPaint;
private String text;
private float rate; public TextProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
initView();
} public TextProgressBar(Context context) {
super(context);
initView();
} private void initView() { mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.BLUE);
} @Override
public synchronized void setProgress(int progress) {
setText(progress);
super.setProgress(progress);
} private void setText(int progress) {
rate = progress * 1.0f / this.getMax();
int i = (int) (rate * 100);
this.text = String.valueOf(i) + "%";
} @Override
protected synchronized void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Rect rect = new Rect();
mPaint.getTextBounds(text, 0, this.text.length(), rect);
// int x = (getWidth()/2) - rect.centerX();
// int y = (getHeight()/2) - rect.centerY();
int x = (int) (getWidth() * rate);
if (x == getWidth()) {
// 如果为百分之百则在左边绘制。
x = getWidth() - rect.right;
} int y = (getHeight() / 2) - rect.top;
mPaint.setTextSize(22);
canvas.drawText(text, x, y, mPaint);
} }

 

xml

    <com.example.my_downloader.TextProgressBar
android:id="@+id/pgb_percentage"
android:layout_width="match_parent"
style="?android:attr/progressBarStyleHorizontal"
android:max="100"
android:layout_height="wrap_content"/>
上一篇:Android自定义进度条


下一篇:Android之进度条2