In the Android application, Activity or Fragment would be the base component for the single page. You can put other UI controls into a single layout xml and inflate it in anActivity or a Fragment . One of the problems is that if the UI is complicated, the Activity or Fragment might also include complicated UI logic. In general case, a single page is a composite of many basic UI controls like TextViewButtonImageView , etc. You need to implement the presentation logic in theActivity or the Fragment even in the ControllerPresenter or ViewModel.

A simple example

Assume that we want to implement a simple digest UI like this

Image for post

A simple digest UI

This widget includes 3 TextViews in a ViewGroup. So we can declare the UI layout in xml like this.

Image for post

Layout xml for digest widget

then we can add the UI setup function in Fragment

Image for post

and thanks new ViewBinding, we don’t need to use findViewById by ourselves. And then we want to add the right arrow icon to the right of Detail TextView and assign the same color and adjust the dimension. So we add one more function to do it.

Image for post

set the right drawable to a TextView

As you can see, this is not unusual in the Android development. If the UI includes many widgets, the fragment will become a fatter because it includes lots of presentation logics. Besides, if we want to reuse the UI widget in another fragment, it would be difficult.

Could we have a better solution? One of them is that we can create a custom view group and use the layout file with a<merge> tag. So we can move presentation logics into the custom view group.

#kotlin #android #ui

Refactoring your Activity or Fragment by using <merge> and custom ViewGroup
1.45 GEEK