ConstraintLayout Groups: be careful about visibility!

Or how I spent an afternoon going crazy.

Adrian Tache
Android Ideas
3 min readMay 2, 2020

--

Update: The new ConstraintLayout beta seems to address some of these issues, so here’s hoping this will be fixed when ConstraintLayout 2.0.0 comes out…

For those who don’t know, a Group is a way to control the visibility of multiple objects inside a ConstraintLayout . Essentially, you tell the Group which layout ids it controls, and by setting the visibility of the group you set the visibility of all the views you referenced inside it. You can also create a Group that contains other Groups , however you like. Here’s the docs for it:

https://developer.android.com/reference/androidx/constraintlayout/widget/Group

So the intended behaviour is pretty much like this:

As I said above, you set the visibility of the group and the views basically inherit that visibility. It’s a neat feature as it enables you to show or hide big parts of your UI without writing a million lines of code.

Let’s see another example:

So, first we group the views by adding their IDs into a group and then… hang on, what just happened?! Am I just going crazy or did the visibility setting that I explicitly set for B get totally ignored just because I added it to a group?

It turns out that views that are added to a group inherit its visibility. Yes, even though the group has no visibility explicitly set. Yes, even though you specified a visibility in the xml or in your code. As long as they’re in a group, they inherit the visibility of that group, no matter what, and the group has a visibility of VISIBLE set by default, just like any view.

So, just to summarize this, the two big limitations of the Group are:

  • all the views or layouts in that Group will forcibly inherit its visibility and ignore their own
  • all the views or layouts in that Group will always have the same visibility

Of course, this also applies to groups that are inside other groups, so if you’re having problems setting the visibility of some view, make sure you haven’t added it to a group by mistake.

To me, this seems like odd behaviour, and I’d very much prefer that groups only affect visibility if it’s manually set, and that views would still be able to change their visibility independently of the group. That way you could use the group to quickly set a visibility but wouldn’t be forced to always respect that setting.

The simple way to use this kind of functionality without the shortcomings is to group those views into a separate layout that you add with include at which point you can still hide whatever view you want in that layout, but also hide or show them all at any point.

Thanks for reading this article. You can connect with me on LinkedIn.

If you liked this article, please hit the clap icon 👏 to show your support.

--

--