APP 端切换浅色/深色模式时,状态栏文字颜色不跟随主题变化:
国产 ROM(小米 MIUI、魅族 Flyme)对系统状态栏 API 做了定制化,@capacitor/status-bar 的 StatusBar.setStyle() 在这些设备上可能被系统 UI 覆盖,导致文字颜色切换不生效。
themeMode 切换
→ Capacitor StatusBar.setStyle() (标准路径,普通 ROM 生效)
→ window.AppStatusBar.setLightStatusBars() (原生兜底,系统级 API,ROM 无法拦截)
overlay 必须用 false — setOverlaysWebView({ overlay: true }) 会破坏深色模式。绝对不要改!
npx cap sync android 同步 Java 源文件,再执行 ./gradlew assembleRelease。
WindowInsetsController,后者用 SYSTEM_UI_FLAG_LIGHT_STATUS_BAR。
android/app/src/main/java/com/zhimaquan/app/MainActivity.java
添加 @JavascriptInterface 桥接类:
private class StatusBarBridge {
@JavascriptInterface
public void setLightStatusBars(final boolean light) {
runOnUiThread(() -> {
// Android 11+ (API 30+): 使用 WindowInsetsController
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowInsetsController insetsController = window.getInsetsController();
insetsController.setSystemBarsAppearance(
light ? WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS : 0,
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
);
}
// Android 6-10 (API 23-29): 使用 SYSTEM_UI_FLAG
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int flags = decorView.getSystemUiVisibility();
if (light) flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
else flags &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
decorView.setSystemUiVisibility(flags);
}
});
}
}
在 onCreate 中注册:
webView.addJavascriptInterface(new StatusBarBridge(), "AppStatusBar");
src/app/App.jsx
useEffect(() => {
let cancelled = false;
const updateStatusBar = async () => {
// 1. Capacitor 标准 API
const { StatusBar, Style } = await import('@capacitor/status-bar');
StatusBar.setOverlaysWebView({ overlay: false }); // ← 绝对不能用 true
if (mode === 'dark') {
StatusBar.setStyle({ style: Style.Light });
StatusBar.setBackgroundColor({ color: '#0d0d2b' });
} else {
StatusBar.setStyle({ style: Style.Dark });
StatusBar.setBackgroundColor({ color: '#ffffff' });
}
// 2. 原生 JS Bridge 兜底(带重试)
const tryBridge = (attempt = 0) => {
if (cancelled) return;
if (window.AppStatusBar) {
// light=true → 浅色状态栏(深色文字),用于浅色模式
// light=false → 深色状态栏(白色文字),用于深色模式
window.AppStatusBar.setLightStatusBars(mode !== 'dark');
} else if (attempt < 10) {
setTimeout(() => tryBridge(attempt + 1), 100);
}
};
tryBridge();
};
updateStatusBar();
return () => { cancelled = true; };
}, [mode]);
# 1. 构建 APP 前端
npx vite build --config vite.config.app.js
# 2. 同步 Capacitor(含 Java 源文件)
npx cap sync android
# 3. 构建 APK(含 Java 编译)
cd android && ./gradlew assembleRelease
# 4. 安装到手机
adb -s [设备序列号] install -r android/app/build/outputs/apk/release/app-release.apk
setOverlaysWebView({ overlay: true }) — 会导致深色模式状态栏文字也不显示
android.view.WindowInsetsController 需要 Android 11+,编译时需处理
build.gradle 中 compileSdk 需 >= 30 才能编译 WindowInsetsController
npx cap sync android
共 1 个版本