2.3.7 ProgressBar(进度条)
核对 Android ProgressBar 的类继承体系、常用 XML 属性与 Java 控制方法、系统内置样式、AnimationDrawable 帧动画替代方案以及自定义圆形进度条 CirclePgBar 的测量与圆弧绘制逻辑。
学完这一章,你能够
- 核对 Android ProgressBar 的类继承体系、常用 XML 属性与 Java 控制方法、系统内置样式、AnimationDrawable 帧动画替代方案以及自定义圆形进度条 CirclePgBar 的测量与圆弧绘制逻辑。
类继承关系、核心属性与系统默认样式
`ProgressBar` 用于在登录请求、文件下载等耗时任务中向用户反馈执行状态或具体完成比例,避免界面卡顿感。从类层级看,`ProgressBar` 直接继承自 `View`,其子类包含 `ContentLoadingProgressBar` 与 `AbsSeekBar`,而后续将学的 `SeekBar` 与 `RatingBar` 均继承自 `AbsSeekBar`,因此共享 `ProgressBar` 的基础进度属性与方法。
`ProgressBar` 的常用 XML 属性包括:`android:max`(进度上限)、`android:progress`(当前主进度)、`android:secondaryProgress`(二级进度,常见于视频缓冲条)、`android:progressDrawable`(轨道绘制资源)、`android:indeterminate`(设为 `true` 时进入不精确循环动画模式)、`android:indeterminateDrawable` 与 `android:indeterminateDuration`(不确定模式的图像与单周期时长)。对应的 Java 方法有 `getMax()`、`getProgress()`、`getSecondaryProgress()`、`incrementProgressBy(int diff)`(自动钳位在 `[0, max]` 区间)、`isIndeterminate()` 与 `setIndeterminate(boolean)`。
系统内置了小/中/大圆形进度条(`Widget.ProgressBar.Small`、默认中型、`Widget.ProgressBar.Large`)以及确定型与不确定型水平进度条(`Widget.ProgressBar.Horizontal`)。本站离线实验验证了全部 5 类样式声明及 `incrementProgressBy` 在上溢与下溢时的 `[0, 100]` 边界钳位行为。
帧动画替代圆形进度条与自定义 CirclePgBar
在不需展示具体百分比的加载场景中,常以连续切图定义 `<animation-list android:oneshot="false">`(标准工程一般存放于 `res/drawable/` 目录),为 12 帧各设 `android:duration="200"`(单轮周期 `2400ms`),将其设为 `ImageView` 的 `src` 后通过 `postDelayed` 取出 `AnimationDrawable` 调用 `ad.start()` 启动循环,并按任务状态切换 `ImageView` 可见性(若直接赋给 `ProgressBar` 的 `indeterminateDrawable`,容器过大时可能出现图案尺寸不可控问题)。来源页面附带的帧动画素材包 `进度条动画素材打包.zip` 因继承的源站停采策略未联网下载,已登记至附件清单。
若需同时呈现精确百分比数字与圆环进度,可继承 `View` 实现自定义 `CirclePgBar`:在 `onMeasure()` 中通过 `MeasureSpec` 处理 `AT_MOST`/`UNSPECIFIED` 模式并返回 `2 * mRadius + mStrokeWidth`(`2 * 200 + 50 = 450px`),而在 `EXACTLY` 模式下直接采用父容器给定尺寸;在 `onDraw()` 中以 `mRect` 居中定位圆弧外接矩形,按 `angle = mProgress / (float) mMax * 360` 从 `-90°`(正上方 12 点钟方向)调用 `canvas.drawArc(...)` 绘制前景弧(进度 `90%` 对应扫掠角 `324.0°`),并绘制居中百分比文字、递增进度触发 `invalidate()` 直到抵达 `mTargetProgress`。在现代 Material Design 项目中,亦可直接使用 `CircularProgressIndicator` 与 `LinearProgressIndicator`。
运行离线 ProgressBar 样式解析、区间钳位、12 帧动画周期及 CirclePgBar 测量与扫掠角核验
展开查看收起
"""Offline Android UI verifier for Ch 28: ProgressBar."""
import json
import xml.etree.ElementTree as ET
ANDROID_NS = "{http://schemas.android.com/apk/res/android}"
PROGRESSBAR_XML = """<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
<ProgressBar style="@android:style/Widget.ProgressBar.Small" />
<ProgressBar />
<ProgressBar style="@android:style/Widget.ProgressBar.Large" />
<ProgressBar style="@android:style/Widget.ProgressBar.Horizontal" android:max="100" android:progress="18" />
<ProgressBar style="@android:style/Widget.ProgressBar.Horizontal" android:indeterminate="true" />
</LinearLayout>
"""
ANIM_LIST_XML = """<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">
<item android:drawable="@drawable/loading_01" android:duration="200"/>
<item android:drawable="@drawable/loading_02" android:duration="200"/>
<item android:drawable="@drawable/loading_03" android:duration="200"/>
<item android:drawable="@drawable/loading_04" android:duration="200"/>
<item android:drawable="@drawable/loading_05" android:duration="200"/>
<item android:drawable="@drawable/loading_06" android:duration="200"/>
<item android:drawable="@drawable/loading_07" android:duration="200"/>
<item android:drawable="@drawable/loading_08" android:duration="200"/>
<item android:drawable="@drawable/loading_09" android:duration="200"/>
<item android:drawable="@drawable/loading_10" android:duration="200"/>
<item android:drawable="@drawable/loading_11" android:duration="200"/>
<item android:drawable="@drawable/loading_12" android:duration="200"/>
</animation-list>
"""
class ProgressBarModel:
def __init__(self, max_val: int = 100, progress: int = 0, secondary: int = 0, indeterminate: bool = False):
self.max_val = max_val
self.progress = progress
self.secondary = secondary
self.indeterminate = indeterminate
def increment_progress_by(self, diff: int) -> int:
self.progress = max(0, min(self.max_val, self.progress + diff))
return self.progress
def main() -> None:
root = ET.fromstring(PROGRESSBAR_XML)
bars = list(root)
c1_actual = {
"widget_count": len(bars),
"horizontal_progress": int(bars[3].attrib[f"{ANDROID_NS}progress"]),
"horizontal_indeterminate": bars[4].attrib[f"{ANDROID_NS}indeterminate"] == "true",
"hierarchy": ["View", "ProgressBar", "AbsSeekBar", "SeekBar/RatingBar"],
}
c1_expected = {
"widget_count": 5,
"horizontal_progress": 18,
"horizontal_indeterminate": True,
"hierarchy": ["View", "ProgressBar", "AbsSeekBar", "SeekBar/RatingBar"],
}
# Case 2: ProgressBar clamping & secondary progress
pb = ProgressBarModel(max_val=100, progress=18, secondary=45)
p1 = pb.increment_progress_by(30) # 48
p2 = pb.increment_progress_by(80) # clamped to 100
p3 = pb.increment_progress_by(-150) # clamped to 0
pb.indeterminate = True
c2_actual = {
"after_plus_30": p1,
"after_overflow": p2,
"after_underflow": p3,
"secondary": pb.secondary,
"indeterminate": pb.indeterminate,
}
c2_expected = {
"after_plus_30": 48,
"after_overflow": 100,
"after_underflow": 0,
"secondary": 45,
"indeterminate": True,
}
# Case 3: AnimationDrawable 12-frame loop cycle
anim = ET.fromstring(ANIM_LIST_XML)
items = anim.findall("item")
durations = [int(it.attrib[f"{ANDROID_NS}duration"]) for it in items]
total_ms = sum(durations)
# Frame at t=500ms (frame 2 -> loading_03) and t=2650ms (wraps 2650 % 2400 = 250 -> frame 1 -> loading_02)
def frame_at(ms: int) -> str:
rem = ms % total_ms
acc = 0
for it, dur in zip(items, durations):
acc += dur
if rem < acc:
return it.attrib[f"{ANDROID_NS}drawable"]
return items[-1].attrib[f"{ANDROID_NS}drawable"]
c3_actual = {
"oneshot": anim.attrib[f"{ANDROID_NS}oneshot"] == "true",
"frame_count": len(items),
"cycle_ms": total_ms,
"at_500ms": frame_at(500),
"at_2650ms": frame_at(2650),
}
c3_expected = {
"oneshot": False,
"frame_count": 12,
"cycle_ms": 2400,
"at_500ms": "@drawable/loading_03",
"at_2650ms": "@drawable/loading_02",
}
# Case 4: Custom CirclePgBar onMeasure & drawArc sweep angle
radius, stroke, max_val, target = 200.0, 50.0, 100, 90
def real_size(mode: str, spec_size: int) -> int:
if mode in ("AT_MOST", "UNSPECIFIED"):
return int(radius * 2 + stroke)
return spec_size
w = real_size("AT_MOST", 600)
h = real_size("EXACTLY", 500)
view_size = int(radius * 2)
left = (w - view_size) // 2
top = (h - view_size) // 2
target_angle = round(target / float(max_val) * 360.0, 1)
c4_actual = {
"measured_wh": [w, h],
"arc_rect": [left, top, left + view_size, top + view_size],
"start_angle_deg": -90,
"target_sweep_deg": target_angle,
}
c4_expected = {
"measured_wh": [450, 500],
"arc_rect": [25, 50, 425, 450],
"start_angle_deg": -90,
"target_sweep_deg": 324.0,
}
cases = [
{
"name": "progressbar_hierarchy_and_xml_styles",
"summary": "解析 5 种系统 ProgressBar 样式并核对 View->ProgressBar->AbsSeekBar 类继承层级",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "progress_clamping_and_increment",
"summary": "验证 incrementProgressBy 上下界钳位、[0, max] 边界及不确定模式切换",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "animation_list_frame_cycle",
"summary": "解析 12 帧 AnimationDrawable animation-list XML 并核算循环周期与任意时刻帧索引",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
{
"name": "circle_pgbar_measure_and_arc_sweep",
"summary": "验证自定义圆形进度条 CirclePgBar 的 MeasureSpec 测量、圆弧外接矩形及 90% 对应 324° 扫掠角",
"expected": c4_expected,
"actual": c4_actual,
"passed": c4_actual == c4_expected,
},
]
print(json.dumps({
"version": "CPython 3.12.14 offline Android UI/XML/Adapter verifier (Android SDK/emulator absent)",
"cases": cases,
}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
Android `Canvas` 极坐标的 `0°` 指向右侧 3 点钟方向且顺时针增加,起始角设为 `-90°` 即可让进度环从顶部 12 点钟方向开始顺时针扫掠。