前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android progressbar实现带底部指示器和文字的进度条

Android progressbar实现带底部指示器和文字的进度条

作者头像
砸漏
发布2020-10-27 14:26:19
1.4K0
发布2020-10-27 14:26:19
举报
文章被收录于专栏:恩蓝脚本

本文实例为大家分享了Android实现带指示器和文字的进度条,供大家参考,具体内容如下

根据项目要求需要实现以下效果:

列出源码:

代码语言:javascript
复制
public class TextProgressBar extends LinearLayout {
 
 String text;
 Paint mPaint;
 private Rect textRect;
 private Bitmap bitmap;
 private ProgressBar progressBar;
 int progress;
 int proWidth, proHeight;
 
 public TextProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
  super(context, attrs, defStyleAttr);
  initText(context);
 }
 
 public TextProgressBar(Context context) {
  super(context);
  initText(context);
 }
 
 public TextProgressBar(Context context, AttributeSet attrs) {
  super(context, attrs);
  initText(context);
 }
 
 @Override
 protected synchronized void onDraw(Canvas canvas) {
  super.onDraw(canvas);
  progress = progressBar.getProgress();
  if (progress == 0 || progress == progressBar.getMax())
   return;
  this.mPaint.getTextBounds(this.text, 0, this.text.length(), textRect);
 
  proWidth = progressBar.getWidth();
  proHeight = progressBar.getHeight();
 
  //画指示器
  int bitmapx = (int) (progressBar.getLeft() + proWidth * ((progress * 1f) / progressBar.getMax())) - bitmap.getWidth() / 2;
  int bitmapy = proHeight + bitmap.getHeight() / 2;
  if (bitmapx < 0)
   bitmapx = progressBar.getLeft();
  if(bitmapx   progressBar.getRight()-bitmap.getWidth())
   bitmapx = progressBar.getRight()-bitmap.getWidth();
  canvas.drawBitmap(bitmap, bitmapx, bitmapy, mPaint);
 
  //写字
  int tvx = (int) (progressBar.getLeft() + proWidth * ((progress * 1f) / progressBar.getMax())) - textRect.centerX();
  int tvy = proHeight + bitmap.getHeight() * 2 + 4;
  if (tvx < 0)
   tvx = progressBar.getLeft();
  if(tvx  = progressBar.getRight()-textRect.width())
   tvx = progressBar.getRight()-textRect.width();
  canvas.drawText(this.text, tvx, tvy + bitmap.getHeight(), this.mPaint);
 
 }
 
 //初始化,画笔
 private void initText(Context context) {
  View inflate = View.inflate(context, R.layout.textprogressbar, this);
  progressBar = (ProgressBar) inflate.findViewById(R.id.progressbar1);
  progressBar.setProgress(50);
  setWillNotDraw(false);
  this.mPaint = new Paint();
  this.mPaint.setColor(getResources().getColor(R.color.red));
  this.mPaint.setTextSize(20);
  textRect = new Rect();
  text = "0";
  bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.progress_top);
 }
 
 public void setProgress(int progress) {
  progressBar.setProgress(progress);
 }
 
 
 public void setText(String str) {
  text = str;
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档