0

When I programmatically create a button as shown below, none of the custom styles are considered and I lose all of the default stylings (such as default background color etc..)

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RelativeLayout layout = (RelativeLayout) findViewById(R.id.activity_main);
    Button button = new Button(this, null, R.style.LocButtonStyle);
    layout.addView(button);
    button.setText("Ok");

}

}

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="LocButtonStyle" parent="@android:style/Widget.Button">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textColor">#FFFFFF</item>
    <item name="android:colorBackground">#ff0000</item>-->
    <item name="android:textSize">160dp</item>
</style>

If I programatically create a Button without the styles the default styling is OK, but that's obviously not what I want.

    Button button = new Button(this);

I have only seen workarounds for this, but I am yet to find the answer why this doesn't work.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Crocodile
  • 5,724
  • 11
  • 41
  • 67
  • you can not set style on programatically created views. – Divyesh Patel Dec 08 '16 at 06:58
  • Why would we have the constructor then to declare the style? https://developer.android.com/reference/android/widget/Button.html#Button(android.content.Context, android.util.AttributeSet, int) – Crocodile Dec 08 '16 at 07:00
  • The third parameter in that `View` constructor expects an `R.attr`, not an `R.style`. The `attr` needs to be defined in your resources, and the style it points to needs to be set in your theme. I'm pretty sure there's a decent post about it here somewhere. I'll try to find it. – Mike M. Dec 08 '16 at 07:04
  • Hmm, maybe I'm misremembering where I saw what I'm thinking of, but [this post](http://stackoverflow.com/a/39280344) at least gives an overview, and makes note of the confusion that parameter has caused. Anyhoo, if you want to apply a style to a dynamically instantiated `View`, you can use a `ContextThemeWrapper` around the `Context` you pass in the constructor. – Mike M. Dec 08 '16 at 07:25
  • I just realized I neglected to mention the four-parameter constructor, which does take an `R.style` as the last argument, but it's only available in API 21+. – Mike M. Dec 08 '16 at 08:00

0 Answers0