2

Here is my style:

<style name="buttonQuestionStyle" parent="@style/Widget.AppCompat.Button.Colored">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:textSize">16sp</item>
    <item name="android:padding">25dp</item>
    <item name="android:layout_margin">10dp</item>
    <item name="android:background">@color/questionButton</item>
</style>

And here my code:

Button btn = new Button(getActivity());
btn.setText(ojb.getText());
if (Build.VERSION.SDK_INT < 23) {
    btn.setTextAppearance(getActivity(), R.style.buttonQuestionStyle);
} else {
    btn.setTextAppearance(R.style.buttonQuestionStyle);
}

In the app:

Programmatically button appears like this: programmatically button

And via layout it worked. Appears like this: xml layout button

Here is my code in the XML Layout:

<Button
    android:text="Question"
    style="@style/buttonQuestionStyle" />

So... I dont know why it happens, and how fix it.

Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96

2 Answers2

7

You can pass a ContextThemeWrapper in constructor for button and use 3 arguments constructor for Button(context, attributeset, defStyle).

ContextThemeWrapper wrapper = new ContextThemeWrapper(this,R.style.buttonQuestionStyle);
Button btn = new Button(wrapper, null, 0); // note this constructor
btn.setText("some text");
mallaudin
  • 4,744
  • 3
  • 36
  • 68
0

Some info around why you cannot set button's style programmatically, as per the JavaDoc of method setTextAppearance

Sets the text appearance from the specified style resource.
 <p>
 Use a framework-defined {@code TextAppearance} style like
 {@link android.R.style#TextAppearance_Material_Body1    @android:style/TextAppearance.Material.Body1}
 or see {@link android.R.styleable#TextAppearance TextAppearance} for the
 set of attributes that can be used in a custom style.
  @param resId the resource identifier of the style to apply
 @attr ref android.R.styleable#TextView_textAppearance

So it deals with only text appearance not other style elements.

Still if you want to apply some style at runtime programmatically you need to

  1. make each and every change separately for example to set background you need to call setBackground and similarly for other cases.

    or

  2. Inflate that view programmatically using that particular theme.

Nayan Srivastava
  • 3,655
  • 3
  • 27
  • 49