
Hello Readers,
In this blog post, we will be seeing in detail about how to change the themes dynamically in Android platform. Theme dependent Resources are used by the system at runtime based on the current theme of the application. A theme can be set to each activity in the app dynamically using the code below:
activity.setTheme(R.style.Theme_LargeText);
The resources can be generated by following the below steps:
1. Create an attrs.xml file which contains the references to the theme dependent resources.
2. Suppose that we have two themes, for example, black and white. Consider that avatar.png is the drawable resource we are going to use in the specified themes.
3. First, create two drawables and name them like avatar_black.png and avatar_white.png.
4. Create reference for the drawables in the attrs.xml as
5. Create styles for the above said two themes in styles.xml and declare the drawable to be used based on the theme as
Black theme:
White theme:
6. Then use the reference for the drawables in the views as:
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
The bolded “avatar” is the reference for the theme dependent resources which is referred at runtime based on the theme.
Likewise, theme dependent color resources can be generated. The steps are same for drawables except that the format should be given as “color” or “color|reference”
If the format as given as “color” then the color resources can be used as follows
Black theme:
White theme:
If the format as given as “color|reference” then the color resources can be used as follows
Declare color values in the colors.xml file as
Declare color values in the colors.xml file as
Black theme:
White theme:
Note: In the above both cases, refer the color resources in the views as
android:background=”?currentColor”
We will be back with some more exciting features in the future posts. What features do you think is exciting and want us to explore? Mention in the comments section.