In this post, we will discuss how to implement a custom view group by extending an existing one, like a FrameLayout. Let’s assume that we are building a layout for displaying user’s avatar. The requirement is if a user has an avatar, show the avatar picture, if not, show their initials as text. So it would be good if we have some kind of AvatarView and Avatar data class (which contains name and avatar picture).
Android Custom View 101
In this installment, we talk about how to implement custom view group. Custom View VS Custom ViewGroup When we think about a view, it is usually very simple and self contained. View represents, draws and handles interaction for a part of the screen. Whereas ViewGroup is more about a binding relationship between views. ViewGroup is a specialized View that contains other Views. It has children. As discussed before, in order for custom view to work correctly, it has to implement two methods: onDraw() and onMeasure(), and there is no need to implement onLayout() cause there is no children to layout.
In this post, we finally gonna take a look at how to implement onMeasure() properly. When implementing a custom view, we should always consider its lower and upper size limit. In this case since the format of the time is fixed (hh:mm:ss). So we just need to get the width and height of it. Suppose we set the MAX_TIME = "00:00:00", then to get its width in pixel we can do:
In Part I, we talked about how to create a simple custom view. But we don’t really implement the onMeasure(). In this post, we will analyze what problems we will have if we omit the onMeasure(). You can think of how the measurements are made as a conversation between the child and parent views. The child tells its parent how it wants to be laid out by using LayoutParams. This can either be set in xml file or programatically.
Creating your own custom android views can be useful and daunting at the same time. For a long time there is nobody really talks about it in a approachable way, until this lady Huyen Tue Dao. Let’s try to follow her approach and create some custom view! In this part, we will create a very simple timer view that takes up the whole screen and display the current time. So let’s get started.