Android Dev Tip #5

When using merge as the root element of the layout of your Compound View, tools:parentTag can help you utilise all the features of the Design tool.

Most of the times, when creating a Compound View you want to inflate the layout xml directly into the created ViewGroup. Without introducing any additional layouts in-between. That’s why you should be really familiar with how merge tag works in layout xmls. Or at least what’s (probably) the most typical use-case of this tag.

The easiest way to understand it, would be:

  • When creating a Compound View:
Image for post
Image for post
  • With R.layout.layout_example_compound_view being:
Image for post
Image for post
  • When the ExampleCompoundView is inflated:

this:

Image for post
Image for post

becomes this:

Image for post
Image for post

By default your layout design tool will not know what is the eventual type your merge tag becomes. This can be a bit annoying if:

a) You like to use the design tool to set some of your View’s parameters.

or

b) You like to peek at the Design visualisation to see if what you’re doing in xml is correct.

Here’s where the parentTag parameter (of the tools namespace) comes in handy. It provides you with a way of telling the Design tool, what will be the eventual ViewGroup of the merge tag.

tools:parentTag="your.package.ExampleCompoundView"

(You will also need to add android:layout_width, android:layout_height to your merge tag for the Design tool to work properly).

For the layout:

Image for post
Image for post

the design tool looks like this:

Image for post
Image for post

It is not aware that the merge tag represents a ConstraintLayout, therefore it cannot take into account any of the enclosed ImageView’s layout parameters (and as a result cannot display anything).

If you add the parentTag parameter to the layout (+ layout_width and layout_height):

Image for post
Image for post

The design tool will understand that the merge tag really is a ConstraintLayout, and it will display the enclosed elements correspondingly:

Image for post
Image for post

Remember that it doesn’t have to be exactly ConstraintLayout. It can be any other ViewGroup (including any compound view of yours that will extend some ViewGroup).

If you enjoyed this post, please show your support! Recommend, follow, comment, share.

This really means a lot!

Image for post
Image for post

senior android engineer @reddit | former android tech lead @getthefabulous | recovering feature creep 💉 | https://github.com/blipinsk

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store