MaterialThemeOverlay

public class MaterialThemeOverlay


Utility to apply a theme overlay to any android.content.Context. The theme overlay is read from an attribute in the style. This is useful to override theme attributes only for the specific view.

The intended use is in a custom view constructor.

public MyCustomView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
}

Summary

Public methods

static Context
wrap(
    Context context,
    AttributeSet set,
    int defStyleAttr,
    int defStyleRes
)

Uses the materialThemeOverlay attribute to create a themed context.

static Context
wrap(
    Context context,
    AttributeSet set,
    int defStyleAttr,
    int defStyleRes,
    int[] optionalAttrs
)

Uses the materialThemeOverlay attribute and optionalAttr attributes to create a combined themed context.

Public methods

wrap

public static Context wrap(
    Context context,
    AttributeSet set,
    int defStyleAttr,
    int defStyleRes
)

Uses the materialThemeOverlay attribute to create a themed context.

This allows us to use MaterialThemeOverlay with a default style, and gives us some protection against losing our ThemeOverlay by clients who set android:theme or app:theme. If android:theme or app:theme is specified by the client, any attributes defined there will take precedence over attributes defined in materialThemeOverlay.

wrap

public static Context wrap(
    Context context,
    AttributeSet set,
    int defStyleAttr,
    int defStyleRes,
    int[] optionalAttrs
)

Uses the materialThemeOverlay attribute and optionalAttr attributes to create a combined themed context.

The final theme overlay will apply materialThemeOverlay first, then the optionalAttr overlays in order.

This facilitates creating locally scoped, re-usable overlays for component variants. For example, if buttons can be one of two colors and one of three shapes, instead of creating a style for each color-shape combination, an overlay can be created for each color and each shape. The button can then wrap its context and pass both overlay attributes to optionalAttrs before reading color and shape values.

See also
wrap