Issue
Is it possible to make margins collapse in Android? Let's say I have a LinearLayout
and add three TextView
s, each with an android:layout_margin
of 10dp
. I get the following result:
src="https://i.stack.imgur.com/lNiY8.png" alt="actual result">
However, I'd like to get this 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?)
Solution
What I typically do to fix this myself, is to simply cut the View's (i.e. your TextView) margin in half, and add that same number as padding to the containing ViewGroup (i.e. your LinearLayout). This way you will end up with even spacing around all items. For example:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dip"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:text="I'm a TextView!"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:text="I'm a TextView!"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:text="I'm a TextView!"
/>
</LinearLayout>
Answered By - Kevin Coppock
Answer Checked By - Timothy Miller (JavaFixing Admin)