1

I have a project with the theme defined in the manifest file. When I use XML to define the views, the theme is inherited and applied, however when I create the views programmatically, no theme is applied. How do I get the theme defined in the manifest file to also apply to activities with programmatic created views?

Here is a code sample. How do I get the manifest theme to propagate to the Button created in the sample?

LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

Button button = new Button(this);
layout.addView(button, params);
setContentView(layout);

Here is the definition from the manifest file:

android:theme="@style/Theme.CustomTheme"

Here is the definition of the CustomTheme in the styles.xml file:

<style name="Theme.CustomTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">

I have tried the following options using the view's constructor:

new LinearLayout(context, null, R.style.Theme_MobileSheriff);
new LinearLayout(context, null, 0, R.style.Theme_MobileSheriff);
new LinearLayout(new ContextThemeWrapper(context, R.style.Theme_MobileSheriff), null, 0, R.style.Theme_MobileSheriff);

I have found several articles on stack overflow asking the same question, but none of them have the answer and all of them have been asked 5+ years ago.

Please assist.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Hendré
  • 262
  • 10
  • 27
  • I think you need to use the four-parameter `LinearLayout` constructor and pass your theme ID as the fourth parameter. See [the corresponding `View` constructor documentation](https://developer.android.com/reference/kotlin/android/view/View.html?hl=en#view_4) for more. – CommonsWare Nov 18 '22 at 13:07
  • @CommonsWare I have already tried the various constructors of LinearLayout. My theme is still not applied. I have also revised my question to include the options I have tired. – Hendré Nov 19 '22 at 11:48

0 Answers0