检测Android设备主题(是暗还是亮)

时间:2016-11-01 09:33:09

标签: android android-theme

您可以为您的应用设置主题,但我想知道是否可以找出设备使用的主题。目前,我的应用使用Theme.AppCompat.Light。我想避免改变主题。

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

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

2 个答案:

答案 0 :(得分: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;
}    

答案 1 :(得分:0)

这可能会有助ContextThemeWrapper

相关问题