Here's XML:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/LightStyle"
android:layout_width="fill_parent"
android:layout_height="55dip"
android:clickable="true"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" />
</RelativeLayout>
How to set style
attribute programmatically?
You cannot set a view's style programmatically yet, but you may find this thread useful.
Update: At the time of answering this question (mid 2012, API level 14-15), setting the view programmatically was not an option (even though there were some non-trivial workarounds)whereas this has been made possible after the more recent API releases. See @Blundell's answer for details.
If you'd like to continue using XML (which the accepted answer doesn't let you do) and set the style after the view has been created you may be able to use the Paris library which supports a subset of all available attributes.
Since you're inflating your view from XML you'd need to specify an id in the layout:
Then when you need to change the style programmatically, after the layout has been inflated:
For more: the list of supported view types and attributes (includes background, padding, margin, etc. and can easily be extended) and installation instructions with additional documentation.
Disclaimer: I'm the original author of said library.
Technically you can apply styles programmatically, with custom views anyway:
The one argument constructor is the one used when you instantiate views programmatically.
So chain this constructor to the super that takes a style parameter.
Or as @Dori pointed out simply:
For a new Button/TextView:
For an existing instance:
For Image or layouts:
I don't propose to use ContextThemeWrapper as it do this:
What can make unwanted results in your application. Instead I propose new library "paris" for this from airbnb guys:
https://github.com/airbnb/paris
This is my simple example, the key is the
ContextThemeWrapper
wrapper, without it, my style does not work, and using the three parameters constructor of the View.