2

I hope I can explain what I'm after. In essence, my users have asked me to allow different looks in my application, which I hope I can do with themes.

I hoped I could do something like this:

<style name="NewTheme" parent="android:Theme.Dark">
  <item name="labelColor">#f90</item>
  <item name="buttonColor">#fff</item>
  <item name="buttonBg">@drawable/button</item>
</style>
<style name="OldTheme" parent="android:Theme.Dark">
  <item name="labelColor">#fa0</item>
  <item name="buttonColor">#88f</item>
  <item name="buttonBg">@drawable/button_old</item>
</style>

And then reference these values in my styles.xml:

<style name="labelStyle">
  <item name="android:textColor>@labelColor</item>
</style>
<style name="buttonStyle">
  <item name="android:textcolor">@buttonColor</item>
  <item name="android:background">@buttonBg</item>
</style>

I know this syntax is wrong, but what might be the right syntax? Basically, I want to create sets of attributes (color, background, a couple other things) and select them based on theme.

Edward Falk
  • 9,991
  • 11
  • 77
  • 112
  • 1
    Why not create a colors.xml, add all your color sets to it and define your individual styles referencing your colors from the XML? That what has always worked for me. – Siddharth Lele May 11 '12 at 03:58
  • Thanks for your help everybody. The short answer turned out to be that I needed to define my meta-values in attrs.xml, e.g. " " – Edward Falk May 11 '12 at 14:29
  • Siddharth, I could put my colors into colors.xml, but how would I change them depending on theme? – Edward Falk May 11 '12 at 15:11
  • @EdwardFalk How can I get the labelColor in my activty? I can get the colors inside colors.xml using below line: getResources().getColor(R.id.labelColor); But how will I get this color if its defined in attr.xml file? – Nitesh Kumar Feb 26 '15 at 07:21

1 Answers1

2

To work with themes and styles in Android you have to:

  1. Define one or more themes in themes.xml and set the definitions of your styles there.

  2. Define custom attributes, a.k.a. custom styles, in attrs.xml.

  3. Describe what the values of your custom styles are in styles.xml.

  4. In your layout files, give your views a style attribute, which has a custom style name as their values.

  5. Set the theme of your application or activity in either AndroidManifest.xml or in the Activity's onCreate(). This is done by calling setTheme() in the activity's onCreate() method, before any call to setContentView().

  6. To change the theme, you simply need to restart your activity.

enter image description here

Iadvice you to look at this tutorial it deals with all that a programmer want to work on android themes (text color, text formatting, state list drawable etc ...)

K_Anas
  • 31,226
  • 9
  • 68
  • 81