Detect the Android device theme (is it dark or light)

你离开我真会死。 提交于 2020-01-24 08:49:45

问题


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. 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);
}

回答1:


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;
}    



回答2:


This might help ContextThemeWrapper



来源:https://stackoverflow.com/questions/40357331/detect-the-android-device-theme-is-it-dark-or-light

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!