蓝色天空网mbsky.com · 知识 · 实践 · 创造Android · 本地阅读预览
教程 / 移动开发 / Android

2.3.9 RatingBar(星级评分条)

核对 Android RatingBar 特有属性(isIndicator、numStars、rating、stepSize)、内置样式、OnRatingBarChangeListener 监听以及利用 layer-list 与自定义 Style 替换评分图标的方法。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

RatingBar 特有属性、内置样式与评分监听

`RatingBar`(星级评分条)与 `SeekBar` 同为 `AbsSeekBar`/`ProgressBar` 的子类,常用于商品评价、服务打分等星级评分交互。除继承 `ProgressBar` 能力外,其核心专有属性有四项:`android:isIndicator`(布尔值,默认 `false`;设为 `true` 时仅作只读展示,禁止用户手动点按修改)、`android:numStars`(显示的星标总数,须为整数)、`android:rating`(默认初始评分,浮点数)以及 `android:stepSize`(每次步进增量,浮点数如 `0.5` 或 `0.1`,决定底层最大步数 `numStars / stepSize`)。系统亦内置了 `?android:attr/ratingBarStyleSmall` 与 `?android:attr/ratingBarStyleIndicator` 两种紧凑只读样式(默认 `isIndicator=true`)。

监听评分变化只需调用 `setOnRatingBarChangeListener` 并重写 `onRatingChanged(ratingBar, rating, fromUser)` 获取最新浮点评分值。本站离线实验实测了 `stepSize=0.5`(底层 `max=10`)与 `stepSize=0.1`(底层 `max=50`)的步进量化与 `[0, numStars]` 钳位,并验证 `isIndicator=true` 会阻断用户触摸改动但仍允许代码调用 `setRating()` 更新展示。

自定义图标与 Style 样式替换

当业务需要将默认五角星替换为笑脸、心形等自定义图标时,可分三步完成:首先编写 `<layer-list>` 资源 `ratingbar_full.xml`,依次将 `@android:id/background`、`@android:id/secondaryProgress` 指向未点亮图标,将 `@android:id/progress` 指向已点亮图标;其次在 `styles.xml` 中声明继承自 `@android:style/Widget.RatingBar` 的自定义样式(如 `roomRatingBar`),覆写 `android:progressDrawable` 并设置与素材高度匹配的 `android:minHeight`/`android:maxHeight`(如 `24dip`);最后在布局中的 `<RatingBar>` 应用 `style="@style/roomRatingBar"` 并设为 `wrap_content`(图标之间的水平间距通常在切图时于素材左右预留透明边距控制)。

运行离线 RatingBar 步进量化、只读指示模式、自定义 layer-list 与 Style 解析核验

python · 阅读源码
"""Offline Android UI verifier for Ch 30: RatingBar."""
import json
import xml.etree.ElementTree as ET

ANDROID_NS = "{http://schemas.android.com/apk/res/android}"

LAYER_LIST_XML = """<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background" android:drawable="@mipmap/ic_rating_off1" />
    <item android:id="@android:id/secondaryProgress" android:drawable="@mipmap/ic_rating_off1" />
    <item android:id="@android:id/progress" android:drawable="@mipmap/ic_rating_on1" />
</layer-list>
"""

STYLE_XML = """<resources>
    <style name="roomRatingBar" parent="@android:style/Widget.RatingBar">
        <item name="android:progressDrawable">@drawable/ratingbar_full</item>
        <item name="android:minHeight">24dip</item>
        <item name="android:maxHeight">24dip</item>
    </style>
</resources>
"""


class RatingBarModel:
    def __init__(self, num_stars: int = 5, step_size: float = 0.5, rating: float = 0.0, is_indicator: bool = False):
        self.num_stars = num_stars
        self.step_size = step_size
        self.is_indicator = is_indicator
        self.rating = 0.0
        self.events = []
        self.set_rating(rating, from_user=False)

    @property
    def internal_max(self) -> int:
        return int(round(self.num_stars / self.step_size))

    def set_rating(self, value: float, from_user: bool = True) -> float:
        if from_user and self.is_indicator:
            return self.rating
        clamped = max(0.0, min(float(self.num_stars), value))
        snapped = round(round(clamped / self.step_size) * self.step_size, 4)
        self.rating = snapped
        self.events.append({"rating": snapped, "fromUser": from_user})
        return self.rating


def main() -> None:
    rb_half = RatingBarModel(num_stars=5, step_size=0.5, rating=2.3)
    rb_tenth = RatingBarModel(num_stars=5, step_size=0.1, rating=4.74)
    rb_half.set_rating(6.2, from_user=True)
    rb_half.set_rating(-1.0, from_user=True)
    c1_actual = {
        "half_step_internal_max": rb_half.internal_max,
        "half_step_trace": [e["rating"] for e in rb_half.events],
        "tenth_step_internal_max": rb_tenth.internal_max,
        "tenth_step_initial": rb_tenth.rating,
    }
    c1_expected = {
        "half_step_internal_max": 10,
        "half_step_trace": [2.5, 5.0, 0.0],
        "tenth_step_internal_max": 50,
        "tenth_step_initial": 4.7,
    }

    # Case 2: isIndicator mode blocks user touch changes while permitting programmatic setRating
    rb_ind = RatingBarModel(num_stars=5, step_size=0.5, rating=3.5, is_indicator=True)
    after_user = rb_ind.set_rating(5.0, from_user=True)
    after_code = rb_ind.set_rating(4.5, from_user=False)
    c2_actual = {
        "after_user_touch": after_user,
        "after_programmatic": after_code,
        "event_count": len(rb_ind.events),
    }
    c2_expected = {
        "after_user_touch": 3.5,
        "after_programmatic": 4.5,
        "event_count": 2,
    }

    # Case 3: Custom layer-list & style XML parsing
    ll = ET.fromstring(LAYER_LIST_XML)
    layer_map = {it.attrib[f"{ANDROID_NS}id"]: it.attrib[f"{ANDROID_NS}drawable"] for it in ll.findall("item")}
    st = ET.fromstring(STYLE_XML).find("style")
    st_items = {it.attrib["name"]: it.text for it in st.findall("item")}
    c3_actual = {
        "layers": layer_map,
        "style_parent": st.attrib["parent"],
        "style_items": st_items,
    }
    c3_expected = {
        "layers": {
            "@android:id/background": "@mipmap/ic_rating_off1",
            "@android:id/secondaryProgress": "@mipmap/ic_rating_off1",
            "@android:id/progress": "@mipmap/ic_rating_on1",
        },
        "style_parent": "@android:style/Widget.RatingBar",
        "style_items": {
            "android:progressDrawable": "@drawable/ratingbar_full",
            "android:minHeight": "24dip",
            "android:maxHeight": "24dip",
        },
    }

    # Case 4: Built-in styles semantics
    builtin_styles = {
        "?android:attr/ratingBarStyleSmall": {"isIndicator_default": True, "interactive": False},
        "?android:attr/ratingBarStyleIndicator": {"isIndicator_default": True, "interactive": False},
        "@android:style/Widget.RatingBar": {"isIndicator_default": False, "interactive": True},
    }
    c4_expected = builtin_styles

    cases = [
        {
            "name": "ratingbar_step_quantization_and_bounds",
            "summary": "验证 RatingBar 的 numStars/stepSize 步进量化、区间钳位及底层 ProgressBar max 换算",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "indicator_mode_and_listener",
            "summary": "验证 isIndicator=true 阻断用户触摸改动但允许代码 setRating 更新的行为",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "layer_list_and_custom_style_xml",
            "summary": "解析自定义图标评分条的 layer-list 三层资源与 roomRatingBar 样式节点",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "ratingbar_builtin_styles_check",
            "summary": "核对系统内置小号与指示器评分条样式默认仅展示不可交互的属性语义",
            "expected": c4_expected,
            "actual": builtin_styles,
            "passed": builtin_styles == 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()
预期结果 · 待实际运行核验
  • 验证 numStars/stepSize 步进吸附与底层 max 换算、isIndicator 触摸阻断以及自定义评分条 layer-list 与样式配置。
运行离线 RatingBar 步进量化、只读指示模式、自定义 layer-list 与 Style 解析核验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:6454191b7a98020aef396243f5d6137eb5187a32b6e482a12ff6e43427bbde0c

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载2.3.9 RatingBar(星级评分条)实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:4af3313fcae87faccb40f18ddfe890dff4bbb436d21a38697740c5e811973dca

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在商品详情页中仅需展示商家已有评分、不允许用户点击篡改,应如何配置 `RatingBar`?

展开参考解答

将 `android:isIndicator="true"`(或直接采用默认只读的 `?android:attr/ratingBarStyleSmall` / `?android:attr/ratingBarStyleIndicator` 样式),再通过代码 `setRating(score)` 设置展示分值。

规范与官方依据