蓝色天空.知识 · 实践 · 创造
我的收藏
Android 教程目录 156章
课程介绍
Android / LEARN BY DOING

3.6 响应系统设置的事件(Configuration 类)

系统核对 android.content.res.Configuration 的关键设备配置字段与常量定义,解析横竖屏切换编程接口及 API 13+ 下 android:configChanges="orientation|screenSize" 的核心生效条件。

学完这一章,你能够

  • 系统核对 android.content.res.Configuration 的关键设备配置字段与常量定义,解析横竖屏切换编程接口及 API 13+ 下 android:configChanges="orientation|screenSize" 的核心生效条件。

Configuration 类的定位与核心属性

`android.content.res.Configuration` 用于描述当前 Android 设备的软硬件环境与系统设置状态(如屏幕方向、像素密度、字体缩放与语言区域),可通过 `getResources().getConfiguration()` 读取当前上下文配置。

`Configuration` 暴露的核心字段包括:`densityDpi`(屏幕像素密度 DPI);`fontScale`(用户字体缩放因子,决定 `sp` 相对 `dp` 的放大倍数);`hardKeyboardHidden`(物理硬键盘隐藏状态,实际框架常量为 `HARDKEYBOARDHIDDEN_UNDEFINED=0`、`HARDKEYBOARDHIDDEN_NO=1`、`HARDKEYBOARDHIDDEN_YES=2`,原笔记误写为 0 和 1);`keyboard`(键盘类型:`KEYBOARD_NOKEYS`、`KEYBOARD_QWERTY`、`KEYBOARD_12KEY`);`keyboardHidden`(整型常量,综合反映软硬键盘是否不可用,而非原笔记所称的 `boolean`);`locale`(当前语言环境,Android 7.0 / API 24 起推荐改用 `getLocales()`);`mcc` 与 `mnc`(移动国家码与移动网络码,共同标识移动运营商);`navigation`(方向导航设备:`NONAV`、`DPAD`、`TRACKBALL`、`WHEEL`);`orientation`(屏幕方向:`ORIENTATION_PORTRAIT=1` 竖屏、`ORIENTATION_LANDSCAPE=2` 横屏);`screenWidthDp`、`screenHeightDp` 与 `smallestScreenWidthDp`(可用宽高及最小宽度,单位 `dp`);`touchscreen`(触摸屏类型:`NOTOUCH`、`STYLUS`、`FINGER`)。

读取设备配置信息示例

在示例 `MainActivity.onCreate()` 中获取 `Configuration cfg = getResources().getConfiguration()` 后,可将各字段拼接展示在 `TextView` 中。审校原代码时需特别修正末三行的一处复制粘贴缺陷:原代码将 `smallestScreenWidthDp`、`touchscreen` 与 `uiMode` 均误拼成了 `cfg.densityDpi`,实际应分别读取 `cfg.smallestScreenWidthDp`、`cfg.touchscreen` 与 `cfg.uiMode`。

重写 onConfigurationChanged 响应横竖屏切换

默认情况下,屏幕旋转等配置变更会销毁并重建 `Activity` 以重新加载对应限定符的资源(如 `layout-land`)。若希望由当前 `Activity` 自行接管而不重建,可重写回调 `onConfigurationChanged(Configuration newConfig)`,并配合 `setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE / PORTRAIT)` 实现按钮切换横竖屏。**API 13+ 关键生效条件澄清**:原笔记提到 `targetSdkVersion` 高于 12 时配置 `android:configChanges="orientation"` 不会触发 `onConfigurationChanged()`,其根本原因在于 **自 Android 3.2(API 13)起,屏幕旋转同时会引起屏幕尺寸变化(`screenSize`)**;因此无需降级 `targetSdkVersion` 到 12,只需在 `AndroidManifest.xml` 的 `<activity>` 标签中声明 `android:configChanges="orientation|screenSize"`(若需兼容分屏/折叠屏再补充 `screenLayout|smallestScreenSize`),即可在所有现代 Android 版本上稳定触发 `onConfigurationChanged()`。此外,`android.permission.CHANGE_CONFIGURATION` 属于系统/开发签名权限,普通应用调用自身的 `setRequestedOrientation()` 或接收 `onConfigurationChanged()` 并不需要申请该权限。本站离线 Python 验证器实测了 `Configuration` 常量校验、横竖屏宽高互换、API 12 与 API 34 下 `configChanges` 重建/回调判定以及 `dp`/`sp` 像素换算。

掌握 `Configuration` 字段读取与 `android:configChanges="orientation|screenSize"` 的版本演进规律,有助于在多屏尺寸、多语言与横竖屏切换场景下编写健壮的 Android 界面。

运行 Configuration 常量核对、横竖屏尺寸互换与 API 13+ configChanges 规则离线验证

含完整源码 · 178 行
展开查看收起
python
"""Offline Android verifier for Ch60: Configuration properties, orientation toggle & configChanges."""
import json
from dataclasses import dataclass

ORIENTATION_PORTRAIT = 1
ORIENTATION_LANDSCAPE = 2
HARDKEYBOARDHIDDEN_UNDEFINED = 0
HARDKEYBOARDHIDDEN_NO = 1
HARDKEYBOARDHIDDEN_YES = 2
KEYBOARD_NOKEYS = 1
KEYBOARD_QWERTY = 2
KEYBOARD_12KEY = 3
NAVIGATION_NONAV = 1
TOUCHSCREEN_FINGER = 3


@dataclass
class Configuration:
    density_dpi: int
    font_scale: float
    hard_keyboard_hidden: int
    keyboard: int
    keyboard_hidden: int
    locale: str
    mcc: int
    mnc: int
    navigation: int
    orientation: int
    screen_width_dp: int
    screen_height_dp: int
    smallest_screen_width_dp: int
    touchscreen: int

    def rotate(self) -> "Configuration":
        new_ori = ORIENTATION_LANDSCAPE if self.orientation == ORIENTATION_PORTRAIT else ORIENTATION_PORTRAIT
        return Configuration(
            density_dpi=self.density_dpi,
            font_scale=self.font_scale,
            hard_keyboard_hidden=self.hard_keyboard_hidden,
            keyboard=self.keyboard,
            keyboard_hidden=self.keyboard_hidden,
            locale=self.locale,
            mcc=self.mcc,
            mnc=self.mnc,
            navigation=self.navigation,
            orientation=new_ori,
            screen_width_dp=self.screen_height_dp,
            screen_height_dp=self.screen_width_dp,
            smallest_screen_width_dp=self.smallest_screen_width_dp,
            touchscreen=self.touchscreen,
        )


def simulate_rotation_lifecycle(target_sdk: int, config_changes: set[str]) -> dict:
    """On API >= 13 (Android 3.2+), rotation triggers both 'orientation' and 'screenSize' diffs."""
    changed_flags = {"orientation", "screenSize"} if target_sdk >= 13 else {"orientation"}
    handled_in_place = changed_flags.issubset(config_changes)
    if handled_in_place:
        return {"activity_recreated": False, "onConfigurationChanged_called": True}
    return {"activity_recreated": True, "onConfigurationChanged_called": False}


def main() -> None:
    cfg = Configuration(
        density_dpi=420,
        font_scale=1.15,
        hard_keyboard_hidden=HARDKEYBOARDHIDDEN_YES,
        keyboard=KEYBOARD_NOKEYS,
        keyboard_hidden=1,
        locale="zh_CN",
        mcc=460,
        mnc=0,
        navigation=NAVIGATION_NONAV,
        orientation=ORIENTATION_PORTRAIT,
        screen_width_dp=411,
        screen_height_dp=891,
        smallest_screen_width_dp=411,
        touchscreen=TOUCHSCREEN_FINGER,
    )

    # Case 1: Configuration field reading & Android constant values
    act1 = {
        "densityDpi": cfg.density_dpi,
        "fontScale": cfg.font_scale,
        "hardKeyboardHidden_constants": [HARDKEYBOARDHIDDEN_UNDEFINED, HARDKEYBOARDHIDDEN_NO, HARDKEYBOARDHIDDEN_YES],
        "mcc_mnc_operator_pair": [cfg.mcc, cfg.mnc],
        "locale": cfg.locale,
        "smallestScreenWidthDp": cfg.smallest_screen_width_dp,
    }
    exp1 = {
        "densityDpi": 420,
        "fontScale": 1.15,
        "hardKeyboardHidden_constants": [0, 1, 2],
        "mcc_mnc_operator_pair": [460, 0],
        "locale": "zh_CN",
        "smallestScreenWidthDp": 411,
    }

    # Case 2: Portrait <-> Landscape orientation toggle & dp swap
    land = cfg.rotate()
    back_port = land.rotate()
    act2 = {
        "portrait_dims": [cfg.orientation, cfg.screen_width_dp, cfg.screen_height_dp],
        "landscape_dims": [land.orientation, land.screen_width_dp, land.screen_height_dp],
        "back_to_portrait": back_port.orientation == ORIENTATION_PORTRAIT,
        "toast_label_land": "横屏" if land.orientation == ORIENTATION_LANDSCAPE else "竖屏",
    }
    exp2 = {
        "portrait_dims": [1, 411, 891],
        "landscape_dims": [2, 891, 411],
        "back_to_portrait": True,
        "toast_label_land": "横屏",
    }

    # Case 3: API 12 vs API 13+ configChanges="orientation" vs "orientation|screenSize"
    act3 = {
        "api12_orientation_only": simulate_rotation_lifecycle(12, {"orientation"}),
        "api34_orientation_only": simulate_rotation_lifecycle(34, {"orientation"}),
        "api34_orientation_and_screenSize": simulate_rotation_lifecycle(34, {"orientation", "screenSize"}),
    }
    exp3 = {
        "api12_orientation_only": {"activity_recreated": False, "onConfigurationChanged_called": True},
        "api34_orientation_only": {"activity_recreated": True, "onConfigurationChanged_called": False},
        "api34_orientation_and_screenSize": {"activity_recreated": False, "onConfigurationChanged_called": True},
    }

    # Case 4: Density & fontScale pixel conversion (dp -> px, sp -> px)
    density = cfg.density_dpi / 160.0
    dp_16_px = round(16 * density, 2)
    sp_16_px = round(16 * density * cfg.font_scale, 2)
    act4 = {"density_factor": round(density, 4), "16dp_in_px": dp_16_px, "16sp_in_px": sp_16_px}
    exp4 = {"density_factor": 2.625, "16dp_in_px": 42.0, "16sp_in_px": 48.3}

    cases = [
        {
            "name": "configuration_fields_and_constants",
            "summary": "验证 Configuration 设备密度、字体缩放、硬键盘常量值(0/1/2)、MCC/MNC 与语言环境字段",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        },
        {
            "name": "orientation_toggle_and_dp_dimensions",
            "summary": "验证横竖屏切换时 orientation 常量与 screenWidthDp/screenHeightDp 互换及提示文案",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        },
        {
            "name": "config_changes_api13_screen_size_rule",
            "summary": "验证 API>=13 仅声明 orientation 会重建 Activity,声明 orientation|screenSize 才回调 onConfigurationChanged",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        },
        {
            "name": "density_dpi_and_font_scale_conversion",
            "summary": "验证 densityDpi=420 与 fontScale=1.15 下 16dp 与 16sp 到像素的换算差异",
            "expected": exp4,
            "actual": act4,
            "passed": act4 == exp4,
        },
    ]
    print(
        json.dumps(
            {
                "version": "CPython 3.12.14 offline Android UI/Event/Handler verifier (Android SDK/emulator absent)",
                "cases": cases,
            },
            ensure_ascii=False,
            indent=2,
        )
    )


if __name__ == "__main__":
    main()
验证硬键盘常量 0/1/2、横竖屏 dp 互换、API 34 仅配 orientation 重建而配 orientation|screenSize 回调及 dp/sp 像素换算。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a1829.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1859.zip

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

自 Android 3.2(API 13)起,屏幕旋转不仅改变 orientation,还会同步触发 screenSize 变更;必须声明 android:configChanges="orientation|screenSize"(折叠屏/多窗口场景建议再加 screenLayout|smallestScreenSize)才能阻止重建并收到 onConfigurationChanged() 回调。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习