Search code examples
androidandroid-layoutandroid-linearlayoutandroid-constraintlayout

How to auto adjust margin between two vertical buttons based on their visibilities?


I have 2 buttons that are aligned vertically in Android XML layout. There is a 16dp space between the two.

I would like that space to toggle based on both buttons' visibilities.

Like this when both are visible (16dp margin between them):

enter image description here

Like this when button 1 is gone (no margins and button 2 shifts up):

enter image description here

Like this when button 2 is gone (no margin below button 1 now):

enter image description here

I tried LinearLayout, ConstraintLayout with vertical chain but didn't find any solution.

Any help would be great.


Solution

  • If you are using ConstraintLayout you can achieve what you want with the layout_goneMarginXXX attributes.

    You can read more about it in the ConstraintLayout doc

    For your problem all you have to do is set:

    ...
    layout_goneMarginBottom="0dp"
    ...