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:
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:
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?)
Margin collapse occurs when vertically adjacent margins of block-level elements collide to share a general margin space. The size of this shared space is dictated by the larger number margin. You can visualize this as an arm wrestling match, where the larger margin will take over and win.
Note that the margins of floating and absolutely positioned elements never collapse.
android:layout_marginTop Specifies extra space on the top side of this view. This space is outside this view's bounds. Margin values should be positive. May be a dimension value, which is a floating point number appended with a unit such as " 14.5sp ".
Margin collapsing only happens to block-level elements. Other than block-level elements no other elements margin can collapse. Here, we have two <p> tags that were inline-block, hence their margin does not collapse. Margin collapsing occurs only when the block elements come in direct contact with each other.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With