Important detail about gone margin in Android’s ConstraintLayout

Oh hey, hello 👋🏻 Hope you’re having a great day. In this article I’ll tell you about gone margins in android and something you should absolutely know about it or you’ll be quite confused why it isn’t working for you.

I needed to align a new View’s top edge with the top edge of another view present in a vertical arrangement, look at this diagram👇🏻

In figure a you can see the C is constrained to the top of B. If B increases its top margin and move away from A (say during an animation or some user interaction), C will also move and maintain the consistency in design.

But what happens if B is gone 😱, looking at figure b, you can see that the result is not good and now C sits with its top edge flush with A’s bottom edge.

This is where I recalled that ConstraintLayout has something called gone margins, and if I apply that to B, it’ll have some margin even when it is gone (stupid me 😛). I added this line to B and built the app.

Only to meet disappointment 😞, nothing happened at all (figure c). I thought this feature might be buggy right now, then going through the documentation I found this about gone margin parameters:

When a position constraint target’s visibility is View.GONE, you can also indicate a different margin value to be used.

This is when it clicked and I said to myself

I had to put the gone margin on C 🤦🏻‍♂️, as soon as I did that, it started working (figure d).

The takeaway here is that one should read the documentation thoroughly while using an API, sometimes you really need to look for the important details. The gone margin is a good to have and saves some of the logic that earlier had to be manually written for use-cases like these.

That was a short story about a recent learning, I plan to share more such stories in future on how I figured out solutions of different problems and the mistakes I made on the way.

Hope you enjoyed it, see you in the next one. Ciao!

Engineering at Gojek| IITRPR | anything/iabhishek1041