经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » Android » 查看文章
Android实现简单的加载进度条
来源:jb51  时间:2021/5/10 8:45:52  对本文有异议

本文实例为大家分享了Android实现简单的加载进度条的具体代码,供大家参考,具体内容如下

1.效果图

2.自定义progressBar

  1. package com.example.myapplication7;
  2. import android.animation.ValueAnimator;
  3. import android.content.Context;
  4. import android.content.res.TypedArray;
  5. import android.graphics.Canvas;
  6. import android.graphics.Color;
  7. import android.graphics.Paint;
  8. import android.graphics.RectF;
  9. import android.os.Bundle;
  10. import android.os.Parcelable;
  11. import android.util.AttributeSet;
  12. import android.view.animation.AccelerateDecelerateInterpolator;
  13. import android.widget.ProgressBar;
  14. import java.lang.annotation.Retention;
  15. import java.lang.annotation.RetentionPolicy;
  16. import androidx.annotation.IntDef;
  17. public class CircleProgressView extends ProgressBar {
  18. private int mReachBarSize = Utils.dp2px(getContext(), 2); // 未完成进度条大小
  19. private int mNormalBarSize = Utils.dp2px(getContext(), 2); // 未完成进度条大小
  20. private int mReachBarColor = Color.parseColor("#108ee9"); // 已完成进度颜色
  21. private int mNormalBarColor = Color.parseColor("#FFD3D6DA"); // 未完成进度颜色
  22. private int mTextSize = Utils.sp2px(getContext(), 14); // 进度值字体大小
  23. private int mTextColor = Color.parseColor("#108ee9"); // 进度的值字体颜色
  24. private float mTextSkewX; // 进度值字体倾斜角度
  25. private String mTextSuffix = "%"; // 进度值前缀
  26. private String mTextPrefix = ""; // 进度值后缀
  27. private boolean mTextVisible = true; // 是否显示进度值
  28. private boolean mReachCapRound; // 画笔是否使用圆角边界,normalStyle下生效
  29. private int mRadius = Utils.dp2px(getContext(), 20); // 半径
  30. private int mStartArc; // 起始角度
  31. private int mInnerBackgroundColor; // 内部背景填充颜色
  32. private int mProgressStyle = ProgressStyle.NORMAL; // 进度风格
  33. private int mInnerPadding = Utils.dp2px(getContext(), 1); // 内部圆与外部圆间距
  34. private int mOuterColor; // 外部圆环颜色
  35. private boolean needDrawInnerBackground; // 是否需要绘制内部背景
  36. private RectF rectF; // 外部圆环绘制区域
  37. private RectF rectInner; // 内部圆环绘制区域
  38. private int mOuterSize = Utils.dp2px(getContext(), 1); // 外层圆环宽度
  39. private Paint mTextPaint; // 绘制进度值字体画笔
  40. private Paint mNormalPaint; // 绘制未完成进度画笔
  41. private Paint mReachPaint; // 绘制已完成进度画笔
  42. private Paint mInnerBackgroundPaint; // 内部背景画笔
  43. private Paint mOutPaint; // 外部圆环画笔
  44. private int mRealWidth;
  45. private int mRealHeight;
  46. @IntDef({ProgressStyle.NORMAL, ProgressStyle.FILL_IN, ProgressStyle.FILL_IN_ARC})
  47. @Retention(RetentionPolicy.SOURCE)
  48. public @interface ProgressStyle {
  49. int NORMAL = 0;
  50. int FILL_IN = 1;
  51. int FILL_IN_ARC = 2;
  52. }
  53. public CircleProgressView(Context context) {
  54. this(context, null);
  55. }
  56. public CircleProgressView(Context context, AttributeSet attrs) {
  57. this(context, attrs, 0);
  58. }
  59. public CircleProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
  60. super(context, attrs, defStyleAttr);
  61. obtainAttributes(attrs);
  62. initPaint();
  63. }
  64. private void initPaint() {
  65. mTextPaint = new Paint();
  66. mTextPaint.setColor(mTextColor);
  67. mTextPaint.setStyle(Paint.Style.FILL);
  68. mTextPaint.setTextSize(mTextSize);
  69. mTextPaint.setTextSkewX(mTextSkewX);
  70. mTextPaint.setAntiAlias(true);
  71. mNormalPaint = new Paint();
  72. mNormalPaint.setColor(mNormalBarColor);
  73. mNormalPaint.setStyle(mProgressStyle == ProgressStyle.FILL_IN_ARC ? Paint.Style.FILL : Paint.Style.STROKE);
  74. mNormalPaint.setAntiAlias(true);
  75. mNormalPaint.setStrokeWidth(mNormalBarSize);
  76. mReachPaint = new Paint();
  77. mReachPaint.setColor(mReachBarColor);
  78. mReachPaint.setStyle(mProgressStyle == ProgressStyle.FILL_IN_ARC ? Paint.Style.FILL : Paint.Style.STROKE);
  79. mReachPaint.setAntiAlias(true);
  80. mReachPaint.setStrokeCap(mReachCapRound ? Paint.Cap.ROUND : Paint.Cap.BUTT);
  81. mReachPaint.setStrokeWidth(mReachBarSize);
  82. if (needDrawInnerBackground) {
  83. mInnerBackgroundPaint = new Paint();
  84. mInnerBackgroundPaint.setStyle(Paint.Style.FILL);
  85. mInnerBackgroundPaint.setAntiAlias(true);
  86. mInnerBackgroundPaint.setColor(mInnerBackgroundColor);
  87. }
  88. if (mProgressStyle == ProgressStyle.FILL_IN_ARC) {
  89. mOutPaint = new Paint();
  90. mOutPaint.setStyle(Paint.Style.STROKE);
  91. mOutPaint.setColor(mOuterColor);
  92. mOutPaint.setStrokeWidth(mOuterSize);
  93. mOutPaint.setAntiAlias(true);
  94. }
  95. }
  96. private void obtainAttributes(AttributeSet attrs) {
  97. TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.CircleProgressView);
  98. mProgressStyle = ta.getInt(R.styleable.CircleProgressView_cpv_progressStyle, ProgressStyle.NORMAL);
  99. // 获取三种风格通用的属性
  100. mNormalBarSize = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_progressNormalSize, mNormalBarSize);
  101. mNormalBarColor = ta.getColor(R.styleable.CircleProgressView_cpv_progressNormalColor, mNormalBarColor);
  102. mReachBarSize = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_progressReachSize, mReachBarSize);
  103. mReachBarColor = ta.getColor(R.styleable.CircleProgressView_cpv_progressReachColor, mReachBarColor);
  104. mTextSize = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_progressTextSize, mTextSize);
  105. mTextColor = ta.getColor(R.styleable.CircleProgressView_cpv_progressTextColor, mTextColor);
  106. mTextSkewX = ta.getDimension(R.styleable.CircleProgressView_cpv_progressTextSkewX, 0);
  107. if (ta.hasValue(R.styleable.CircleProgressView_cpv_progressTextSuffix)) {
  108. mTextSuffix = ta.getString(R.styleable.CircleProgressView_cpv_progressTextSuffix);
  109. }
  110. if (ta.hasValue(R.styleable.CircleProgressView_cpv_progressTextPrefix)) {
  111. mTextPrefix = ta.getString(R.styleable.CircleProgressView_cpv_progressTextPrefix);
  112. }
  113. mTextVisible = ta.getBoolean(R.styleable.CircleProgressView_cpv_progressTextVisible, mTextVisible);
  114. mRadius = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_radius, mRadius);
  115. rectF = new RectF(-mRadius, -mRadius, mRadius, mRadius);
  116. switch (mProgressStyle) {
  117. case ProgressStyle.FILL_IN:
  118. mReachBarSize = 0;
  119. mNormalBarSize = 0;
  120. mOuterSize = 0;
  121. break;
  122. case ProgressStyle.FILL_IN_ARC:
  123. mStartArc = ta.getInt(R.styleable.CircleProgressView_cpv_progressStartArc, 0) + 270;
  124. mInnerPadding = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_innerPadding, mInnerPadding);
  125. mOuterColor = ta.getColor(R.styleable.CircleProgressView_cpv_outerColor, mReachBarColor);
  126. mOuterSize = (int) ta.getDimension(R.styleable.CircleProgressView_cpv_outerSize, mOuterSize);
  127. mReachBarSize = 0;// 将画笔大小重置为0
  128. mNormalBarSize = 0;
  129. if (!ta.hasValue(R.styleable.CircleProgressView_cpv_progressNormalColor)) {
  130. mNormalBarColor = Color.TRANSPARENT;
  131. }
  132. int mInnerRadius = mRadius - mOuterSize / 2 - mInnerPadding;
  133. rectInner = new RectF(-mInnerRadius, -mInnerRadius, mInnerRadius, mInnerRadius);
  134. break;
  135. case ProgressStyle.NORMAL:
  136. mReachCapRound = ta.getBoolean(R.styleable.CircleProgressView_cpv_reachCapRound, true);
  137. mStartArc = ta.getInt(R.styleable.CircleProgressView_cpv_progressStartArc, 0) + 270;
  138. if (ta.hasValue(R.styleable.CircleProgressView_cpv_innerBackgroundColor)) {
  139. mInnerBackgroundColor = ta.getColor(R.styleable.CircleProgressView_cpv_innerBackgroundColor, Color.argb(0, 0, 0, 0));
  140. needDrawInnerBackground = true;
  141. }
  142. break;
  143. }
  144. ta.recycle();
  145. }
  146. @Override
  147. protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  148. int maxBarPaintWidth = Math.max(mReachBarSize, mNormalBarSize);
  149. int maxPaintWidth = Math.max(maxBarPaintWidth, mOuterSize);
  150. int height = 0;
  151. int width = 0;
  152. switch (mProgressStyle) {
  153. case ProgressStyle.FILL_IN:
  154. height = getPaddingTop() + getPaddingBottom() // 边距
  155. + Math.abs(mRadius * 2); // 直径
  156. width = getPaddingLeft() + getPaddingRight() // 边距
  157. + Math.abs(mRadius * 2); // 直径
  158. break;
  159. case ProgressStyle.FILL_IN_ARC:
  160. height = getPaddingTop() + getPaddingBottom() // 边距
  161. + Math.abs(mRadius * 2) // 直径
  162. + maxPaintWidth;// 边框
  163. width = getPaddingLeft() + getPaddingRight() // 边距
  164. + Math.abs(mRadius * 2) // 直径
  165. + maxPaintWidth;// 边框
  166. break;
  167. case ProgressStyle.NORMAL:
  168. height = getPaddingTop() + getPaddingBottom() // 边距
  169. + Math.abs(mRadius * 2) // 直径
  170. + maxBarPaintWidth;// 边框
  171. width = getPaddingLeft() + getPaddingRight() // 边距
  172. + Math.abs(mRadius * 2) // 直径
  173. + maxBarPaintWidth;// 边框
  174. break;
  175. }
  176. mRealWidth = resolveSize(width, widthMeasureSpec);
  177. mRealHeight = resolveSize(height, heightMeasureSpec);
  178. setMeasuredDimension(mRealWidth, mRealHeight);
  179. }
  180. @Override
  181. protected synchronized void onDraw(Canvas canvas) {
  182. switch (mProgressStyle) {
  183. case ProgressStyle.NORMAL:
  184. drawNormalCircle(canvas);
  185. break;
  186. case ProgressStyle.FILL_IN:
  187. drawFillInCircle(canvas);
  188. break;
  189. case ProgressStyle.FILL_IN_ARC:
  190. drawFillInArcCircle(canvas);
  191. break;
  192. }
  193. }
  194. /**
  195. * 绘制PROGRESS_STYLE_FILL_IN_ARC圆形
  196. */
  197. private void drawFillInArcCircle(Canvas canvas) {
  198. canvas.save();
  199. canvas.translate(mRealWidth / 2, mRealHeight / 2);
  200. // 绘制外层圆环
  201. canvas.drawArc(rectF, 0, 360, false, mOutPaint);
  202. // 绘制内层进度实心圆弧
  203. // 内层圆弧半径
  204. float reachArc = getProgress() * 1.0f / getMax() * 360;
  205. canvas.drawArc(rectInner, mStartArc, reachArc, true, mReachPaint);
  206. // 绘制未到达进度
  207. if (reachArc != 360) {
  208. canvas.drawArc(rectInner, reachArc + mStartArc, 360 - reachArc, true, mNormalPaint);
  209. }
  210. canvas.restore();
  211. }
  212. /**
  213. * 绘制PROGRESS_STYLE_FILL_IN圆形
  214. */
  215. private void drawFillInCircle(Canvas canvas) {
  216. canvas.save();
  217. canvas.translate(mRealWidth / 2, mRealHeight / 2);
  218. float progressY = getProgress() * 1.0f / getMax() * (mRadius * 2);
  219. float angle = (float) (Math.acos((mRadius - progressY) / mRadius) * 180 / Math.PI);
  220. float startAngle = 90 + angle;
  221. float sweepAngle = 360 - angle * 2;
  222. // 绘制未到达区域
  223. rectF = new RectF(-mRadius, -mRadius, mRadius, mRadius);
  224. mNormalPaint.setStyle(Paint.Style.FILL);
  225. canvas.drawArc(rectF, startAngle, sweepAngle, false, mNormalPaint);
  226. // 翻转180度绘制已到达区域
  227. canvas.rotate(180);
  228. mReachPaint.setStyle(Paint.Style.FILL);
  229. canvas.drawArc(rectF, 270 - angle, angle * 2, false, mReachPaint);
  230. // 文字显示在最上层最后绘制
  231. canvas.rotate(180);
  232. // 绘制文字
  233. if (mTextVisible) {
  234. String text = mTextPrefix + getProgress() + mTextSuffix;
  235. float textWidth = mTextPaint.measureText(text);
  236. float textHeight = (mTextPaint.descent() + mTextPaint.ascent());
  237. canvas.drawText(text, -textWidth / 2, -textHeight / 2, mTextPaint);
  238. }
  239. }
  240. /**
  241. * 绘制PROGRESS_STYLE_NORMAL圆形
  242. */
  243. private void drawNormalCircle(Canvas canvas) {
  244. canvas.save();
  245. canvas.translate(mRealWidth / 2, mRealHeight / 2);
  246. // 绘制内部圆形背景色
  247. if (needDrawInnerBackground) {
  248. canvas.drawCircle(0, 0, mRadius - Math.min(mReachBarSize, mNormalBarSize) / 2,
  249. mInnerBackgroundPaint);
  250. }
  251. // 绘制文字
  252. if (mTextVisible) {
  253. String text = mTextPrefix + getProgress() + mTextSuffix;
  254. float textWidth = mTextPaint.measureText(text);
  255. float textHeight = (mTextPaint.descent() + mTextPaint.ascent());
  256. canvas.drawText(text, -textWidth / 2, -textHeight / 2, mTextPaint);
  257. }
  258. // 计算进度值
  259. float reachArc = getProgress() * 1.0f / getMax() * 360;
  260. // 绘制未到达进度
  261. if (reachArc != 360) {
  262. canvas.drawArc(rectF, reachArc + mStartArc, 360 - reachArc, false, mNormalPaint);
  263. }
  264. // 绘制已到达进度
  265. canvas.drawArc(rectF, mStartArc, reachArc, false, mReachPaint);
  266. canvas.restore();
  267. }
  268. /**
  269. * 动画进度(0-当前进度)
  270. *
  271. * @param duration 动画时长
  272. */
  273. public void runProgressAnim(long duration) {
  274. setProgressInTime(0, duration);
  275. }
  276. /**
  277. * @param progress 进度值
  278. * @param duration 动画播放时间
  279. */
  280. public void setProgressInTime(final int progress, final long duration) {
  281. setProgressInTime(progress, getProgress(), duration);
  282. }
  283. /**
  284. * @param startProgress 起始进度
  285. * @param progress 进度值
  286. * @param duration 动画播放时间
  287. */
  288. public void setProgressInTime(int startProgress, final int progress, final long duration) {
  289. ValueAnimator valueAnimator = ValueAnimator.ofInt(startProgress, progress);
  290. valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
  291. @Override
  292. public void onAnimationUpdate(ValueAnimator animator) {
  293. //获得当前动画的进度值,整型,1-100之间
  294. int currentValue = (Integer) animator.getAnimatedValue();
  295. setProgress(currentValue);
  296. }
  297. });
  298. AccelerateDecelerateInterpolator interpolator = new AccelerateDecelerateInterpolator();
  299. valueAnimator.setInterpolator(interpolator);
  300. valueAnimator.setDuration(duration);
  301. valueAnimator.start();
  302. }
  303. public int getReachBarSize() {
  304. return mReachBarSize;
  305. }
  306. public void setReachBarSize(int reachBarSize) {
  307. mReachBarSize = Utils.dp2px(getContext(), reachBarSize);
  308. invalidate();
  309. }
  310. public int getNormalBarSize() {
  311. return mNormalBarSize;
  312. }
  313. public void setNormalBarSize(int normalBarSize) {
  314. mNormalBarSize = Utils.dp2px(getContext(), normalBarSize);
  315. invalidate();
  316. }
  317. public int getReachBarColor() {
  318. return mReachBarColor;
  319. }
  320. public void setReachBarColor(int reachBarColor) {
  321. mReachBarColor = reachBarColor;
  322. invalidate();
  323. }
  324. public int getNormalBarColor() {
  325. return mNormalBarColor;
  326. }
  327. public void setNormalBarColor(int normalBarColor) {
  328. mNormalBarColor = normalBarColor;
  329. invalidate();
  330. }
  331. public int getTextSize() {
  332. return mTextSize;
  333. }
  334. public void setTextSize(int textSize) {
  335. mTextSize = Utils.sp2px(getContext(), textSize);
  336. invalidate();
  337. }
  338. public int getTextColor() {
  339. return mTextColor;
  340. }
  341. public void setTextColor(int textColor) {
  342. mTextColor = textColor;
  343. invalidate();
  344. }
  345. public float getTextSkewX() {
  346. return mTextSkewX;
  347. }
  348. public void setTextSkewX(float textSkewX) {
  349. mTextSkewX = textSkewX;
  350. invalidate();
  351. }
  352. public String getTextSuffix() {
  353. return mTextSuffix;
  354. }
  355. public void setTextSuffix(String textSuffix) {
  356. mTextSuffix = textSuffix;
  357. invalidate();
  358. }
  359. public String getTextPrefix() {
  360. return mTextPrefix;
  361. }
  362. public void setTextPrefix(String textPrefix) {
  363. mTextPrefix = textPrefix;
  364. invalidate();
  365. }
  366. public boolean isTextVisible() {
  367. return mTextVisible;
  368. }
  369. public void setTextVisible(boolean textVisible) {
  370. mTextVisible = textVisible;
  371. invalidate();
  372. }
  373. public boolean isReachCapRound() {
  374. return mReachCapRound;
  375. }
  376. public void setReachCapRound(boolean reachCapRound) {
  377. mReachCapRound = reachCapRound;
  378. invalidate();
  379. }
  380. public int getRadius() {
  381. return mRadius;
  382. }
  383. public void setRadius(int radius) {
  384. mRadius = Utils.dp2px(getContext(), radius);
  385. invalidate();
  386. }
  387. public int getStartArc() {
  388. return mStartArc;
  389. }
  390. public void setStartArc(int startArc) {
  391. mStartArc = startArc;
  392. invalidate();
  393. }
  394. public int getInnerBackgroundColor() {
  395. return mInnerBackgroundColor;
  396. }
  397. public void setInnerBackgroundColor(int innerBackgroundColor) {
  398. mInnerBackgroundColor = innerBackgroundColor;
  399. invalidate();
  400. }
  401. public int getProgressStyle() {
  402. return mProgressStyle;
  403. }
  404. public void setProgressStyle(int progressStyle) {
  405. mProgressStyle = progressStyle;
  406. invalidate();
  407. }
  408. public int getInnerPadding() {
  409. return mInnerPadding;
  410. }
  411. public void setInnerPadding(int innerPadding) {
  412. mInnerPadding = Utils.dp2px(getContext(), innerPadding);
  413. int mInnerRadius = mRadius - mOuterSize / 2 - mInnerPadding;
  414. rectInner = new RectF(-mInnerRadius, -mInnerRadius, mInnerRadius, mInnerRadius);
  415. invalidate();
  416. }
  417. public int getOuterColor() {
  418. return mOuterColor;
  419. }
  420. public void setOuterColor(int outerColor) {
  421. mOuterColor = outerColor;
  422. invalidate();
  423. }
  424. public int getOuterSize() {
  425. return mOuterSize;
  426. }
  427. public void setOuterSize(int outerSize) {
  428. mOuterSize = Utils.dp2px(getContext(), outerSize);
  429. invalidate();
  430. }
  431. private static final String STATE = "state";
  432. private static final String PROGRESS_STYLE = "progressStyle";
  433. private static final String TEXT_COLOR = "textColor";
  434. private static final String TEXT_SIZE = "textSize";
  435. private static final String TEXT_SKEW_X = "textSkewX";
  436. private static final String TEXT_VISIBLE = "textVisible";
  437. private static final String TEXT_SUFFIX = "textSuffix";
  438. private static final String TEXT_PREFIX = "textPrefix";
  439. private static final String REACH_BAR_COLOR = "reachBarColor";
  440. private static final String REACH_BAR_SIZE = "reachBarSize";
  441. private static final String NORMAL_BAR_COLOR = "normalBarColor";
  442. private static final String NORMAL_BAR_SIZE = "normalBarSize";
  443. private static final String IS_REACH_CAP_ROUND = "isReachCapRound";
  444. private static final String RADIUS = "radius";
  445. private static final String START_ARC = "startArc";
  446. private static final String INNER_BG_COLOR = "innerBgColor";
  447. private static final String INNER_PADDING = "innerPadding";
  448. private static final String OUTER_COLOR = "outerColor";
  449. private static final String OUTER_SIZE = "outerSize";
  450. @Override
  451. public Parcelable onSaveInstanceState() {
  452. final Bundle bundle = new Bundle();
  453. bundle.putParcelable(STATE, super.onSaveInstanceState());
  454. // 保存当前样式
  455. bundle.putInt(PROGRESS_STYLE, getProgressStyle());
  456. bundle.putInt(RADIUS, getRadius());
  457. bundle.putBoolean(IS_REACH_CAP_ROUND, isReachCapRound());
  458. bundle.putInt(START_ARC, getStartArc());
  459. bundle.putInt(INNER_BG_COLOR, getInnerBackgroundColor());
  460. bundle.putInt(INNER_PADDING, getInnerPadding());
  461. bundle.putInt(OUTER_COLOR, getOuterColor());
  462. bundle.putInt(OUTER_SIZE, getOuterSize());
  463. // 保存text信息
  464. bundle.putInt(TEXT_COLOR, getTextColor());
  465. bundle.putInt(TEXT_SIZE, getTextSize());
  466. bundle.putFloat(TEXT_SKEW_X, getTextSkewX());
  467. bundle.putBoolean(TEXT_VISIBLE, isTextVisible());
  468. bundle.putString(TEXT_SUFFIX, getTextSuffix());
  469. bundle.putString(TEXT_PREFIX, getTextPrefix());
  470. // 保存已到达进度信息
  471. bundle.putInt(REACH_BAR_COLOR, getReachBarColor());
  472. bundle.putInt(REACH_BAR_SIZE, getReachBarSize());
  473. // 保存未到达进度信息
  474. bundle.putInt(NORMAL_BAR_COLOR, getNormalBarColor());
  475. bundle.putInt(NORMAL_BAR_SIZE, getNormalBarSize());
  476. return bundle;
  477. }
  478. @Override
  479. public void onRestoreInstanceState(Parcelable state) {
  480. if (state instanceof Bundle) {
  481. final Bundle bundle = (Bundle) state;
  482. mProgressStyle = bundle.getInt(PROGRESS_STYLE);
  483. mRadius = bundle.getInt(RADIUS);
  484. mReachCapRound = bundle.getBoolean(IS_REACH_CAP_ROUND);
  485. mStartArc = bundle.getInt(START_ARC);
  486. mInnerBackgroundColor = bundle.getInt(INNER_BG_COLOR);
  487. mInnerPadding = bundle.getInt(INNER_PADDING);
  488. mOuterColor = bundle.getInt(OUTER_COLOR);
  489. mOuterSize = bundle.getInt(OUTER_SIZE);
  490. mTextColor = bundle.getInt(TEXT_COLOR);
  491. mTextSize = bundle.getInt(TEXT_SIZE);
  492. mTextSkewX = bundle.getFloat(TEXT_SKEW_X);
  493. mTextVisible = bundle.getBoolean(TEXT_VISIBLE);
  494. mTextSuffix = bundle.getString(TEXT_SUFFIX);
  495. mTextPrefix = bundle.getString(TEXT_PREFIX);
  496. mReachBarColor = bundle.getInt(REACH_BAR_COLOR);
  497. mReachBarSize = bundle.getInt(REACH_BAR_SIZE);
  498. mNormalBarColor = bundle.getInt(NORMAL_BAR_COLOR);
  499. mNormalBarSize = bundle.getInt(NORMAL_BAR_SIZE);
  500. initPaint();
  501. super.onRestoreInstanceState(bundle.getParcelable(STATE));
  502. return;
  503. }
  504. super.onRestoreInstanceState(state);
  505. }
  506. @Override
  507. public void invalidate() {
  508. initPaint();
  509. super.invalidate();
  510. }
  511. }

3.设置宽高

  1. package com.example.myapplication7;
  2. import android.content.Context;
  3. import android.graphics.Bitmap;
  4. import android.graphics.Canvas;
  5. import android.graphics.Color;
  6. import android.graphics.Paint;
  7. import android.graphics.RectF;
  8. import android.graphics.drawable.BitmapDrawable;
  9. import android.graphics.drawable.Drawable;
  10. import android.text.TextUtils;
  11. import android.util.DisplayMetrics;
  12. import android.view.WindowManager;
  13. import java.util.Collection;
  14. import androidx.annotation.ColorRes;
  15. public class Utils {
  16. private static WindowManager windowManager;
  17. private static WindowManager getWindowManager(Context context) {
  18. if (windowManager == null) {
  19. windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
  20. }
  21. return windowManager;
  22. }
  23. public static float getDensity(Context context) {
  24. return context.getResources().getDisplayMetrics().density;
  25. }
  26. public static float getFontDensity(Context context) {
  27. return context.getResources().getDisplayMetrics().scaledDensity;
  28. }
  29. public static DisplayMetrics getDisplayMetrics(Context context) {
  30. DisplayMetrics displayMetrics = new DisplayMetrics();
  31. getWindowManager(context).getDefaultDisplay().getMetrics(displayMetrics);
  32. return displayMetrics;
  33. }
  34. public static int dp2px(Context context, float dp) {
  35. return (int) (getDensity(context) * dp + 0.5f);
  36. }
  37. public static int px2dp(Context context, float px) {
  38. return (int) (px / getDensity(context) + 0.5f);
  39. }
  40. public static int sp2px(Context context, float sp) {
  41. return (int) (getFontDensity(context) * sp + 0.5f);
  42. }
  43. public static int px2sp(Context context, float px) {
  44. return (int) (px / getFontDensity(context) + 0.5f);
  45. }
  46. public static int getWindowWidth(Context context) {
  47. return getDisplayMetrics(context).widthPixels;
  48. }
  49. public static int getWindowHeight(Context context) {
  50. return getDisplayMetrics(context).heightPixels;
  51. }
  52. public static String getPathFormat(String path) {
  53. if (!TextUtils.isEmpty(path)) {
  54. int lastPeriodIndex = path.lastIndexOf('.');
  55. if (lastPeriodIndex > 0 && lastPeriodIndex + 1 < path.length()) {
  56. String format = path.substring(lastPeriodIndex + 1);
  57. if (!TextUtils.isEmpty(format)) {
  58. return format.toLowerCase();
  59. }
  60. }
  61. }
  62. return "";
  63. }
  64. public static boolean isGif(String url) {
  65. return "gif".equals(getPathFormat(url));
  66. }
  67. public static Bitmap getTextBitmap(Context context, int width, int height, int radius, String text, int textSize, @ColorRes int bgColor) {
  68. radius = dp2px(context, radius);
  69. Bitmap bitmap = Bitmap.createBitmap(dp2px(context, width), dp2px(context, height), Bitmap.Config.ARGB_8888);
  70. Canvas canvas = new Canvas(bitmap);
  71. RectF rect = new RectF(0, 0, canvas.getWidth(), canvas.getHeight());
  72. Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  73. paint.setColor(context.getResources().getColor(bgColor));
  74. canvas.drawRoundRect(new RectF(0, 0, rect.width(), rect.height()), radius, radius, paint);
  75. paint.setColor(Color.WHITE);
  76. paint.setTextSize(dp2px(context, textSize));
  77. paint.setTextAlign(Paint.Align.CENTER);
  78. Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
  79. float baseline = (rect.bottom + rect.top - fontMetrics.bottom - fontMetrics.top) / 2;
  80. canvas.drawText(text, rect.centerX(), baseline, paint);
  81. return bitmap;
  82. }
  83. public static Drawable getTextDrawable(Context context, int width, int height, int radius, String text, int textSize, @ColorRes int bgColor) {
  84. return new BitmapDrawable(getTextBitmap(context, width, height, radius, text, textSize, bgColor));
  85. }
  86. public static boolean isEmpty(Collection<?> collection) {
  87. return collection == null || collection.isEmpty();
  88. }
  89. public static int getSize(Collection<?> collection) {
  90. return collection == null ? 0 : collection.size();
  91. }
  92. }

4.主界面

  1. package com.example.myapplication7;
  2. import android.graphics.Bitmap;
  3. import android.graphics.Color;
  4. import android.os.Bundle;
  5. import android.os.Handler;
  6. import android.os.Message;
  7. import android.util.Log;
  8. import android.view.View;
  9. import androidx.annotation.NonNull;
  10. import androidx.annotation.Nullable;
  11. import androidx.appcompat.app.AppCompatActivity;
  12. public class MainActivity extends AppCompatActivity {
  13. private String fileName;
  14. private CircleProgressView progressView;
  15. private Bitmap bitmap;
  16. private int i = 0;
  17. final Handler handler = new Handler(new Handler.Callback() {
  18. @Override
  19. public boolean handleMessage(@NonNull Message msg) {
  20. if (msg.what == 1) {
  21. //do something
  22. int a = (int) msg.obj;
  23. Log.e("TAG", "handleMessage" + a);
  24. progressView.setProgress(a * 10);
  25. if (a == 10) {
  26. progressView.setVisibility(View.GONE);
  27. }
  28. }
  29. return false;
  30. }
  31. });
  32. @Override
  33. protected void onCreate(@Nullable Bundle savedInstanceState) {
  34. super.onCreate(savedInstanceState);
  35. setContentView(R.layout.activity_main);
  36. progressView = findViewById(R.id.progressView);
  37. getWindow().setTitleColor(Color.rgb(65, 183, 216));
  38. //主线程中调用:
  39. new Thread(new MyThread()).start();
  40. }
  41. class MyThread extends Thread {//这里也可用Runnable接口实现
  42. @Override
  43. public void run() {
  44. while (true) {
  45. try {
  46. Thread.sleep(500);//每隔1s执行一次
  47. Message msg = new Message();
  48. msg.what = 1;
  49. i++;
  50. msg.obj = i;
  51. handler.sendMessage(msg);
  52. } catch (InterruptedException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. }
  57. }
  58. }

5.布局

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:orientation="vertical">
  7. <com.example.myapplication7.CircleProgressView
  8. android:id="@+id/progressView"
  9. android:layout_width="150dp"
  10. android:layout_height="150dp"
  11. android:progress="0"
  12. app:cpv_innerPadding="2dp"
  13. app:cpv_outerColor="@android:color/darker_gray"
  14. app:cpv_outerSize="1dp"
  15. app:cpv_progressNormalColor="@android:color/darker_gray"
  16. app:cpv_progressReachColor="@color/white"
  17. app:cpv_progressStyle="FillInnerArc" />
  18. </LinearLayout>

6.资源文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <declare-styleable name="CircleProgressView">
  4. <attr name="cpv_progressNormalColor" format="color" />
  5. <attr name="cpv_progressReachColor" format="color" />
  6. <attr name="cpv_progressTextColor" format="color" />
  7. <attr name="cpv_progressTextSize" format="dimension" />
  8. <attr name="cpv_progressTextOffset" format="dimension" />
  9. <attr name="cpv_progressNormalSize" format="dimension" />
  10. <attr name="cpv_progressReachSize" format="dimension" />
  11. <attr name="cpv_radius" format="dimension" />
  12. <attr name="cpv_progressTextVisible" format="boolean" />
  13. <attr name="cpv_progressStartArc" format="integer" />
  14. <attr name="cpv_progressTextSkewX" format="dimension" />
  15. <attr name="cpv_progressTextPrefix" format="string" />
  16. <attr name="cpv_progressTextSuffix" format="string" />
  17. <attr name="cpv_innerBackgroundColor" format="color" />
  18. <attr name="cpv_progressStyle" format="enum">
  19. <enum name="Normal" value="0" />
  20. <enum name="FillInner" value="1" />
  21. <enum name="FillInnerArc" value="2" />
  22. </attr>
  23. <attr name="cpv_innerProgressColor" format="color" />
  24. <attr name="cpv_innerPadding" format="dimension" />
  25. <attr name="cpv_outerColor" format="color" />
  26. <attr name="cpv_outerSize" format="dimension" />
  27. <attr name="cpv_reachCapRound" format="boolean" />
  28. </declare-styleable>
  29. </resources>

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号