How do you programmatically set a Style on a View?

Posted by Greg on Stack Overflow See other posts from Stack Overflow or by Greg
Published on 2010-12-23T21:22:36Z Indexed on 2010/12/23 23:54 UTC
Read the original article Hit count: 233

Filed under:
|

I would like to do something like this:

<Button
 android:id="@+id/button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_cotent"
 style="@style/SubmitButtonType"
/>

But in code

The xml approach works fine provided that SubmitButtonType is defined. Now what I assume happens is that the appt parser runs through this xml, generates an AttributeSet. That AttributeSet when passed to context/theme#obtainStyledAttributes() will have the style ref mask anything that is not written inline in this tag. Great that's fine! Now how do we do this programmatically.

Button, as well as other View types, has a constructor that has the form:

<Widget>(Context context, AttributeSet set, int defStyle).

So I thought this would work.

 Button button = new Button(context, null, R.style.SubmitButtonType);

However, I am finding that defStyle is badly documented as it really should be written to be a resourceId to an attribute (from R.attrs) that will be passed to obtainStyledAttributes() as the attribute resource, and not the style resource. After looking at the code, all the view implementations seem to pass 0 as the styleRef. I don't see the harm in having it passed as both the attr and the style resource (more flexible and negligible overhead)

However I might be approaching this all wrong. How do you do this in code then other than by setting each individual element of the style to the specific widget you want to style (only possible by looking a the code to see what param maps to which method or set of methods).


The only way I have found to do this is:

<declare-styleable>
<attr name="totallyAdhoc_attribute_just_for_this_case" format="reference">
</declare-styleable>

<style name="MyAlreadyExistantTheme" >
  ...
  ...
  <item name="totallyAdhoc_attribute_just_for_this_case">@style/SubmitButtonType</item>
</style>

And instead of passing R.style.SubmitButtonType as defStyle, I pass the new R.attr.totallyAdhoc_attribute_just_for_this_case.

Button button = new Button(context, null, R.attr.totallyAdhoc_attribute_just_for_this_case);

This works but sounds way too complicated.

© Stack Overflow or respective owner

Related posts about android

Related posts about android-widget