Skip to content

Create a Custom View with ViewModel as Datasource | Android Developement

MVVM is current default pattern that created when we build new project in Android Studio. With MVVM we easily manage our service especialy for maintaining even though on the development we need to prepare more files.

In the development process, we often meet with a common view that will appear in some place. For a small project base, its OK if you create it manualy in each parent view, but for a huge scale project i think that is a bad practice. What is the solution? Yap, using a Custom View. Making a custom view is not a dificult case i think, but how to create a custom view that contain a view model for fetching data requirement?

Here we will learning together about how to Create a Custom View with ViewModel as Datasource, but i assump that you are already familiar with MVVM pattern

First

Let’s create a simple view for our custom view. Here we will make a view that will showing a data from your endpoint, so we just create a textview. Create a xml file in yoir project and named with layout_custom_view.xml

Oke, so we just create a textview widget for an example and give the textview id with text_user_name that will showing user name from the endpoint.

Second

Create a custom class that will be used on parent view on next step. Here i give the file class name with CustomView.kt

I think in the code above is already clear with the comments that already added. So we define viewModel as a lazy variable and init view on init methode and change YourViewModelClass with your view model. Then we setup our listener on onAttachedToWindow and setup the view on function setupView that passing data from our view model.

Last Step

After we create layout and the custom view class, now we can use our custom view inside the parent view xml. For example is like that:

So we just including our custom view like code above. Simple isn’t it?

Thanks for reading this article. If you have another best practice, please add to the comments block.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.