steventnorris
steventnorris

Reputation: 5896

Adding Button Programmatically Does not Adhere to Text Color

I have a button style as below:

<style name="ButtonAppTheme" parent="android:Widget.Holo.Light.Button">
      <!-- ORIGINAL: <item name="android:background">@drawable/apptheme_btn_default_holo_light</item> -->
      <item name="android:background">@drawable/x_button_background</item>
      <item name="android:textColor">@drawable/x_button_text</item>
      <item name="android:textSize">@dimen/master_fontsize_mid</item>
      <item name="android:paddingLeft">@dimen/button_padleft</item>
      <item name="android:paddingRight">@dimen/button_padright</item>
      <item name="android:singleLine">true</item>
  </style>

It is set in the theme as below:

<item name="android:buttonStyle">@style/ButtonAppTheme</item>

I set this theme in my manifest for my application. However, when I add a button programmatically like this:

btn = new Button(activity);
LayoutParams params = new LayoutParams(R.dimen.button_height, LayoutParams.MATCH_PARENT);
btn.setLayoutParams(params);
btn.setText("MyButton");
layout.addView(btn);

The background drawable renders fine, but the text is white, not the drawable (grey and red depending on state) that it is supposed to be. How can I ensure my programmatically added buttons are going to adhere fully to this style?

Upvotes: 1

Views: 49

Answers (1)

Sagar Zala
Sagar Zala

Reputation: 5134

Use below code:

 <Button
     android:id="@+id/button1"
     style="@style/ButtonAppTheme"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Button" />

Programmatically,

Button b = new Button(getApplicationContext(), null, R.style.ButtonAppTheme);

Upvotes: 1

Related Questions