Sunday 28 December 2014

Android: Custom theme in android application.


Adding demo here to create custom theme in Android application and applying it.


  • Custom Theme
This is a very simple demo app to create custom theme in android application.

First create two xml files in values folder...
attrs.xml
themes.xml

In attrs.xml file you will define all the attributes we are going to use as a theme style.
e.g:
<resources>
    <attr name="pageBackground" format="reference" />
</resources>



In themes.xml file we will differentiate this attribute according to our themes.
e.g:
<resources>

    <style name="Theme" parent="android:Theme.Light"></style>

    <style name="Theme.Red">
        <item name="launcherBackground">@style/launcher_background_red</item>
    </style>

    <style name="Theme.Green">
        <item name="launcherBackground">@style/launcher_background_green</item>
    </style>

    <style name="Theme.Blue">
        <item name="launcherBackground">@style/launcher_background_blue</item>
    </style>
</resources>



In styles.xml file we will define actual implementation of different themes and set different property and its value accordingly.

<resources xmlns:android="http://schemas.android.com/apk/res/android">

<!-- Red Theme Start -->
<style name="launcher_background_red">
  <item name="android:background">@drawable/images_1</item>
  </style>
<!-- Red Theme End -->


<!-- Green Theme Start -->
<style name="launcher_background_green">
  <item name="android:background">@drawable/images_2</item>
  </style>
<!-- Green Theme End -->


<!-- Blue Theme Start -->
<style name="launcher_background_blue">
  <item name="android:background">@drawable/images_3</item>
  </style>
<!-- Blue Theme End -->

</resources>




Style:
After adding themes we can set style in our xml layout property like below:::
style="?launcherBackground" // We have added this as attribute in attrs.xml
e.g:

<RelativeLayout style="?launcherBackground">
</RelativeLayout>



Applying Theme:
Now for applying theme in our application we have to set theme in activities like below:::
setTheme(R.style.Theme_Red);

I have added one BaseActivity so that when we will change theme in BaseActivity it will reflect to all the child activities.


We have added theme setting in preference so that when user will relaunch application, application will show in previously selected theme.



You can download demo code from below url:
https://drive.google.com/file/d/0B0mH97AUwQqhclhSdkgtajhGVkU/view?usp=sharing