0

How does one go about setting styles of layouts and components from Java code? Something like the following is what I want to do:

button.setStyle(R.style.MyStyle);
Cœur
  • 37,241
  • 25
  • 195
  • 267
ArmaAK
  • 587
  • 6
  • 21

1 Answers1

1

You can't apply style on view programmatically. Though you can do runtime inflating like below.

Create "template.xml" layout file. Which has layout of TextView with style. You can create more then one to support different style.

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Template"
    style="@style/first_style" />

In activity you can inflate this layout by following code.

TextView txtView = (TextView)getLayoutInflater().inflate(R.layout.template, null);
Chintan Rathod
  • 25,864
  • 13
  • 83
  • 93
  • 1
    @ArmaAK i think it is possible search on stackoverflow http://stackoverflow.com/questions/11422220/android-how-to-programmatically-set-the-button-style-in-a-linearlayout – Raghunandan Jan 30 '14 at 05:43
  • Wow, I missed that somehow when I was initially looking. That's not causing the app to crash, but it also isn't showing. I'll have to see if I can get that working. Thanks. – ArmaAK Jan 30 '14 at 05:49
  • 1
    For example setting button text style `button.setTextAppearance(ActivityName.this, R.style.AppBaseTheme);` still you need to define styles in styles.xml and read https://groups.google.com/forum/#!msg/android-developers/P6vfKr5tqlY/X6204pvErjIJ Romain Guy's quote – Raghunandan Jan 30 '14 at 05:49
  • I'm able to add the buttons (using Chintan's method), but the padding and size parameters aren't being set correctly for some reason. I don't really _need_ to do this programmatically, I just wanted to avoid a repetitive xml file. Anyway, thanks for the help. – ArmaAK Jan 30 '14 at 06:32