Search code examples
androidstylesthemessnackbar

How to change an android theme programatically only to the snackbar?


I want to change the theme of the my custom snackbar

public class CustomSnackbar extends BaseTransientBottomBar<CustomSnackbar> {
  public CustomSnackbar(
      CoordinatorLayout parent,
      View contentView,
      BaseTransientBottomBar.ContentViewCallback contentViewCallback) {
    super(parent, contentView, contentViewCallback);
  }

i see in the layout it can be set as:

   android:theme="@style/Theme.my.WithDarkTextButton"

I have tried to set the theme grammatically but found no equivalent:

contentView.setTheme is missing. doesn't evey xml attribute can be set via code?


Solution

  • If you're using a LayoutInflater, then you have to set the theme in XML.

    If you programmatically create a View:

    View contentView = new View(context);
    

    Then change it a little bit:

    View contentView = new View(new ContextThemeWrapper(context, R.style.Theme_my_WithDarkTextButton);
    

    You can't set the theme on-demand. The View only reads the theme attributes when it's constructed.