Android. Apply multiple styles to CustomView via Theme.

Alex Misiulia
AndroidPub
Published in
2 min readJan 27, 2020
Photo by Heng Films on Unsplash

Today I will show you how to apply multiple styles to Views inside the CustomView.

Global plan is:

1. Create CustomView

2. Create custom attributes for each component inside it

3. Create Theme and apply it to CustomView anywhere in the code

I will create just simple View which consists two texts. Kotlin class:

We need to create two attributes to pass styles to each TextView inside our widget separately. Custom attributes file:

attrs.xml

And also layout file for this widget which refers to these custom attrs :

And the last step that we need to accomplish is to add this CustomView to MainActivity and pass the styles via theme to it.

First we need to create styles for this. I am super lazy that’s why I hardcoded colors inside styles.xml (don’t do it in production code):

And after that just add widget to activity_main.xml applying the theme:

And after that just set some text from MainActivity class to demonstrate that I am not a liar and everything works :

Result:

Talk is cheap. Show me the code ©.

Here is the link to the repository. Happy codding!

My name is Alex Misiulia and I am passionate about tech (especially Android). Feel free to reach me on LinkedIn and ask questions about Android development.

--

--