检测Android设备主题(深色还是浅色) [英] Detect the Android device theme (is it dark or light)

查看:727
本文介绍了检测Android设备主题(深色还是浅色)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以为您的应用设置主题,但是我想知道是否有可能找出设备使用了哪个主题.当前,我的应用程序使用Theme.AppCompat.Light.我想避免更改主题.

You can set the theme for your app, but I'm wondering if it's possible to find out which one is used by the device. Currently, my app uses Theme.AppCompat.Light. I'd like to avoid changing the theme.

P.S.我已经尝试将其设置为Theme.DeviceDefault并使用反射来访问其ID,但到目前为止还没有运气.

P.S. I've already tried to set it to Theme.DeviceDefault and access its ID using reflection, but no luck so far.

try {
    setTheme(android.R.style.Theme_DeviceDefault);

    Class<Context> contextClass = Context.class;
    Method getThemeMethod = contextClass.getMethod("getThemeResId");
    getThemeMethod.setAccessible(true);
    Log.d("Test", "" + getThemeMethod.invoke(this)); // Always returns 0

    PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
    Log.d("Test", getResources().getResourceEntryName(packageInfo.applicationInfo.theme)); // Returns 'Theme.DeviceDefault'
} catch (Exception e) {
    Log.d("Test", "exception", e);
}

推荐答案

int currentNightMode = getContext().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;  
switch (currentNightMode) {
    case Configuration.UI_MODE_NIGHT_NO:
        // Night mode is not active, we're using the light theme
        break;
    case Configuration.UI_MODE_NIGHT_YES:
        // Night mode is active, we're using dark theme
        break;
}    

这篇关于检测Android设备主题(深色还是浅色)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆