Reputation: 430
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
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;
}
}
Upvotes: 28
Views: 12548
Reputation: 38121
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.
Upvotes: 9
Reputation: 1006779
Try using getResourceEntryName()
or getResourceName()
on Resources
(typically retrieved via getResources()
), depending on what you are aiming for.
Upvotes: 19
Reputation: 34765
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
Upvotes: -3