Collapsing margins in Android layouts

Viewed 3053

Is it possible to make margins collapse in Android? Let's say I have a LinearLayout and add three TextViews, each with an android:layout_margin of 10dp. I get the following result:

actual result

However, I'd like to get this result:

expected result

I know that I could workaround this by setting different top/bottom margins for the different items:

  • set the top margin of the first item and the bottom margin of the last item to 10dp,
  • set the remainding top/bottom margins to 5dp,

but that makes the design more complicated (especially if the TextViews are dynamically created). Is there some way to make the margins behave like in CSS? (For an explanation of why this makes sense, see: What is the point of CSS collapsing margins?)

2 Answers

Posting a solution for someone who might need this in future. Works for static as well as AdapterViews where list items are dynamic.

Example parent container:

<RecyclerView
     ----
     android:padding_top="10dp"
     android:padding_start="10dp"
     android:padding_end="10dp"
     ---- 
>
</RecyclerView>

The padding ensures the spacing from top, left & right of the window.

Only thing remaining now is the vertical gap between two consecutive children & bottom gap after last child.

Example child / item view:

<RelativeLayout
     ----
     android:margin_bottom="10dp"
     ----
>
     <DynamicChild1 />
     <DynamicChild2 />
</RelativeLayout>

For this question specifically, the child view will just be a TextView with bottom margin.

This will give you the exact output as expected in the question.

Related