ARTICLE

Change Theme of Layout Runtime by Button Click in Android

Posted by Chintan Rathod Articles | Android Programming April 06, 2012
In this article, we will see how to change the layout theme of an Android application at runtime by clicking on a button.
Reader Level:
Download Files:
 

Introduction

In this article, we will see how to change the layout theme of an Android application at runtime by clicking on a button.

What is Theme?

In your mobile, in the display settings, there is an option to set your whole mobile theme like light blue color theme, red color theme or any other. This will set your full mobile functionality with this theme setting.

In Android, to set the theme of an Android application, you need to understand what style is.

Style is an XML file residing in the "project/res/values" directory. This file generally contains settings of appearances. The general structure of "style.xml" is like below:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="nameOfTheTheme">
        <item name="android:attributeSets">value</item>
    </style
>
</resources>

Here, you can see that in the style tag, there is one attribute named "name" which has the value that determines the "name of theme", for example, "MyTheme".

Next is an "item" tag. This tag contains the various attribute sets of views such as "android:textColor"," android:textSize" etc. First define this attribute and then write the value corresponding to it. Let's see an example of a style.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyTheme">
        <item name="android:textColor">#FF0000</item>
    </style
>
</resources>


Here, in the example, you can see that the name of the style is "MyTheme" and the item tag has the attribute "textColor" having value "#FF0000" which is the color "Red".

Now to set the theme while your activity is loading, write the following code before setting your layout file in "setContentView".

activity.setTheme(R.style.MyTheme);
setContentView(R.layout.
main);

This will set your application theme before loading layout. Now you see what style is and how to set the style as the theme of your application. Now follow the steps to create this application.

Step 1

Create an Android project and name it "ChangeTheme" and then right-click on the project. Select "New -> Android XML File". This will open the following dialog box to give the name of that XML file. First select type as "Values" and give "style.xml" as the name of the file.

AndXML1.jpg

Now, open that file, and add the following code into that file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="FirstTheme" >
        <item name="android:textColor">#FF0000</item>
    </style>
    <style name="SecondTheme" >
        <item name="android:textColor">#00FF00</item>
    </style>
    <style name="Thirdheme" >
        <item name="android:textColor">#0000F0</item>
    </style>
</
resources
>

In this file, you can see that I have created 3 styles namely "FirstThem", "SecondTheme" and "ThirdTheme" with the same attribute "textColor" but with different color values.

Step 2

Now, open your "main.xml" layout file which resides in "res/layout" directory.

And put following code to add 3 buttons and 1 label in it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello C-Sharp"
 android:textAppearance="?android:attr/textAppearanceLarge"
/>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="First Theme"
/>

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Second Theme"
/>

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Third Theme"
/>

</LinearLayout>

After writing this code into it, go to the "graphical" view and you can see the following screen.

AndXML2.jpg

Step 3

Open your activity file. In my case it is the "ChangeThemeActivity.java" file which resides in the "src/package" directory.

To set the theme at runtime, we need to bind buttons and give "OnClickListener" to them. So to do that, write down the following code into that file.

---------------------------------
ChangeThemeActivity.java
---------------------------------

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import
android.view.View.OnClickListener;

public class ChangeThemeActivity extends Activity implements OnClickListener
{
   
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
       
super.onCreate(savedInstanceState);
        Utils.onActivityCreateSetTheme(this);
        setContentView(R.layout.
main);
         
                    findViewById(R.id.
button1).setOnClickListener(this);
          findViewById(R.id.
button2).setOnClickListener(this);
          findViewById(R.id.
button3).setOnClickListener(this
);
    }

     @Override
     public void onClick(View v)
     {
         
// TODO Auto-generated method stub
          switch
(v.getId())
          {

          case R.id.button1:
          Utils.changeToTheme(
this, Utils.THEME_DEFAULT);
         
break;
         
case R.id.button2:
          Utils.changeToTheme(
this, Utils.THEME_WHITE);
         
break;
         
case R.id.button3:
          Utils.changeToTheme(
this, Utils.THEME_BLUE);
         
break
;
          }
     }
}

You might think what is "Utils"? The "Utils" class has code to change themes at runtime by calling some activity methods. To create that class, right-click on the project then select "new->class". This will ask you to enter the name of that Java file. Give "Utils" as the name of that Java file. This will create a Java file in the "src" directory under your "package".

Now write the following code in the "Utils" file:

------------------
Utils.java
------------------

import android.app.Activity;
import
android.content.Intent;

public class Utils
{
    
private static int sTheme
;

     public final static int THEME_DEFAULT = 0;
    
public final static int THEME_WHITE = 1;
    
public final static int THEME_BLUE
= 2;

     /**
      * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
      */
     public static void changeToTheme(Activity activity, int theme)
     {
         
sTheme
= theme;
          activity.finish();

activity.startActivity(new Intent(activity, activity.getClass()));

     }

     /** Set the theme of the activity, according to the configuration. */
     public static void onActivityCreateSetTheme(Activity activity)
     {
         
switch (sTheme)
          {
         
default:
         
case THEME_DEFAULT:
              activity.setTheme(R.style.
FirstTheme);
             
break;
         
case THEME_WHITE:
              activity.setTheme(R.style.
SecondTheme);
             
break;
         
case THEME_BLUE:
              activity.setTheme(R.style.
Thirdheme);
             
break
;
          }
     }
}

Description

  1. changeToTheme ( Activity activity, int theme )

    This method has two arguments. First is "Activity", which gives this method to the identify of which the activity has called this method and of whose theme to change. And the second argument is "Theme" id which is already declared in the beginning of the class. Which is:

    public final static int THEME_DEFAULT = 0;
    public final static int THEME_WHITE = 1;
    public final static int THEME_BLUE
    = 2;

    Because we have 3 themes, to identify each of them, we declare 3 constants.
     

  2. onActivityCreateSetTheme ( Activity activity )

    This method is responsible for setting the theme to the activity. After setting the "theme" id into "changeToTheme", this method will check which theme to set. Using a switch case, this will identify it. And as described in the beginning of this tutorial, it will call the "setTheme" method.

Step 4

Now, you are ready to execute this application. But before execution, be sure that you have "AVD" (Android Virtual Device) added in your eclipse. If not, then go to "Window -> AVD Manager" and add a new AVD device to it.

To start execution, right-click on your "project" and select "Run As -> Android Application". This will execute your application in the emulator.

AndXML3.jpg

AndXML4.jpg

Summary

In this brief tutorial, we discussed how create styles and how to use it as a theme of an application and also how to change a theme of an application at runtime.

COMMENT USING