UsingpackageInfo.applicationInfo.theme
将返回整个应用程序的主题,而不是每个活动。这是 hacky,但应该获得当前活动/上下文的主题:
public static String getThemeName(Context context, Resources.Theme theme) {
try {
int mThemeResId;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Field fThemeImpl = theme.getClass().getDeclaredField("mThemeImpl");
if (!fThemeImpl.isAccessible()) fThemeImpl.setAccessible(true);
Object mThemeImpl = fThemeImpl.get(theme);
Field fThemeResId = mThemeImpl.getClass().getDeclaredField("mThemeResId");
if(!fThemeResId.isAccessible())fThemeResId.setAccessible(true);
mThemeResId = fThemeResId.getInt(mThemeImpl);
} else {
Field fThemeResId = theme.getClass().getDeclaredField("mThemeResId");
if(!fThemeResId.isAccessible())fThemeResId.setAccessible(true);
mThemeResId = fThemeResId.getInt(theme);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return theme.getResources().getResourceEntryName(mThemeResId);
}
return context.getResources().getResourceEntryName(mThemeResId);
} catch (Exception e) {
// Theme returned by application#getTheme() is always Theme.DeviceDefault
return "Theme.DeviceDefault";
}
}
我知道这是一个老问题,但我想我会添加我的发现。