0

I had a static button which I had to change to code but when I changed it and specified the same theme in code by R.style.ThemeOverlay_MyDarkButton I found that no style is getting applied.

So I changed the following

   <LinearLayout
      android:id="@+id/buttons_pane"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal"
      android:weightSum="3.0">
      <Button
        android:id="@+id/button_start_verification"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1.0"
        android:text="@string/start_phone_auth"
        android:theme="@style/ThemeOverlay.MyDarkButton"/>
  </LinearLayout>

and

mStartButton = (Button) findViewById(R.id.button_start_verification);

to

  <LinearLayout
      android:id="@+id/buttons_pane"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal"
      android:weightSum="3.0">
  </LinearLayout>

and

    LinearLayout buttons_pane = findViewById(R.id.buttons_pane);
    mStartButton = new Button(this, null, R.style.ThemeOverlay_MyDarkButton);
    mStartButton.setText(R.string.start_phone_auth);
    mStartButton.setLayoutParams(new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1.0f));
    mStartButton.setId(R.id.button_start_verification);
    buttons_pane.addView(mStartButton);

PS: I am aware of the way to set style using an drawable xml as background image (Android Button Styling Programmatically) but my question is how can I do it using theme

ishandutta2007
  • 16,676
  • 16
  • 93
  • 129

1 Answers1

4

Your button's style and theme are two different things. The button you are creating programmatically is more like setting

    style="@style/ThemeOverlay.MyDarkButton"

rather than the

    android:theme="@style/ThemeOverlay.MyDarkButton"

that you want.

You can apply a theme programmatically by using a ContextThemeWrapper.

    Context themedContext = new ContextThemeWrapper(this,
            R.style.ThemeOverlay_MyDarkButton);
    mStartButton = new Button(themedContext);
nick allen
  • 282
  • 3
  • 10