Android: How to obtain the resource ID of the current theme?

Solution 1:

I found a way to solve the requirement without getting the resource id.

I'm adding an item to each of my themes with the name of the string:

<item name="themeName">dark</item>

And in the code I check the name like so:

TypedValue outValue = new TypedValue();
getTheme().resolveAttribute(R.attr.themeName, outValue, true);
if ("dark".equals(outValue.string)) {
   ...
}

Solution 2:

OK here's one puzzle piece: we can get the default theme, as set in the AndroidManifest.xml, as context.getApplicationInfo().theme for the theme set at application level, and from within an Activity, as getPackageManager().getActivityInfo(getComponentName(), 0).theme for that activity.

I guess that gives us a starting point to do our own wrapper for a custom getTheme() and setTheme().

Still that feels like working around rather than with the API. So I'll leave the question open to see if someone comes up with a better idea.

EDIT: There's

getPackageManager().getActivityInfo(getComponentName(), 0).getThemeResource()

which will automatically fallback to application theme if the activity doesn't override it.