diff --git a/lib/java/com/google/android/material/internal/ThemeEnforcement.java b/lib/java/com/google/android/material/internal/ThemeEnforcement.java index b78fe1bb3..3990fc942 100644 --- a/lib/java/com/google/android/material/internal/ThemeEnforcement.java +++ b/lib/java/com/google/android/material/internal/ThemeEnforcement.java @@ -231,10 +231,6 @@ public final class ThemeEnforcement { * defStyleAttr to use a theme overlay if one has been defined. */ public static Context createThemedContext(Context context, int defStyleAttr) { - if (context instanceof ContextThemeWrapper) { - return context; - } - TypedArray a = context.getTheme().obtainStyledAttributes(new int[] {defStyleAttr}); int style = a.getResourceId(0 /* index */, 0 /* defaultVal */); a.recycle(); @@ -244,6 +240,16 @@ public final class ThemeEnforcement { return context; } - return new ContextThemeWrapper(context, style); + a = context.obtainStyledAttributes(style, new int[] {android.R.attr.theme}); + int themeId = a.getResourceId(0 /* index */, 0 /* defaultVal */); + a.recycle(); + + if (themeId != 0 && (!(context instanceof ContextThemeWrapper) + || ((ContextThemeWrapper) context).getThemeResId() != themeId)) { + // If the context isn't a ContextThemeWrapper, or it is but does not have + // the same theme as we need, wrap it in a new wrapper + context = new ContextThemeWrapper(context, themeId); + } + return context; } }