Stack Overflow archive
9 score

Android theme name from theme ID

score
9
question views
12.7K
license
CC BY-SA 3.0

Using packageInfo.applicationInfo.theme will return the theme for the entire app and not each activity. This is hacky, but should get the theme for the current activity/context:

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

I know this is an old question, but thought I would add my findings.

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.