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"/>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。