28

I need to know the name of the current theme, I already have the theme's resource ID. Anybody knows how to get the current theme's name?

Thanks


Solution

public String getThemeName()
{
    PackageInfo packageInfo;
    try
    {
        packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
        int themeResId = packageInfo.applicationInfo.theme;
        return getResources().getResourceEntryName(themeResId);
    }
    catch (NameNotFoundException e)
    {
        return null;
    }
}
d_r
  • 421
  • 1
  • 4
  • 9

3 Answers3

18

Try using getResourceEntryName() or getResourceName() on Resources (typically retrieved via getResources()), depending on what you are aiming for.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
9

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:

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.

Jared Rummler
  • 37,824
  • 19
  • 133
  • 148
  • Why Theme returned by `getThemeName(application, application.getTheme())` is always `Theme.DeviceDefault` ? It's also `Theme.DeviceDefault` if I set `android:theme="@style/AppTheme"` to `application` tag – NickUnuchek May 03 '21 at 13:07
  • Doesn't work in Android 12: No field mThemeResId in class Landroid/content/res/ResourcesImpl$ThemeImpl; (declaration of 'android.content.res.ResourcesImpl$ThemeImpl' appears in /system/framework/framework.jar) – Alexey Ozerov Sep 02 '23 at 09:57
-3

try the below line of code to get the resource name from resource id

getResources().getString(resource id); 

Refer this LINK you may get some ideas how to do

Community
  • 1
  • 1
Shankar Agarwal
  • 34,573
  • 7
  • 66
  • 64