Issue
Demo of negative margin:
The scenario
Overlapping views by setting a negative margin to one of them so that it invades the bounding box of another view.
Thoughts
It seems to work the way you'd expect with overlapping of the layouts if they should. But I don't want to run into a bigger problem for unknowingly not doing things right. Emulators, physical devices, you name it, when you use negative margins everything seems to work correctly, one view invades another's views bounding box and depending on how it's declared in the layout it will be above or below the other view.
I'm also aware that since API 21 we can set the translationZ
and elevation
attributes to make view appear above or below other views but my concern basically comes from the fact that in the documentation for the layout_margin
attributes it's clearly specified that margin values should be positive, let me quote:
Excerpt:
Specifies extra space on the left, top, right and bottom sides of this view. This space is outside this view's bounds. Margin values should be positive. Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters)...
In the years since originally asking this question I haven't had any issues with negative margins, did try to avoid using them as much as possible, but did not encounter any issues, so even though the documentation states that, I'm not too worried about it.
Solution
In 2010, @RomainGuy (core Android engineer) stated that negative margins had unspecified behavior.
In 2011, @RomainGuy stated that you can use negative margins on LinearLayout
and RelativeLayout
.
In 2016, @RomainGuy stated that they have never been officially supported and won't be supported by ConstraintLayout
.
It is easy to work around this limitation though.
Add a helper view (height 0dp, width constrained to parent) at the bottom of your base view, at the bottom add the margin you want.
Then position your view below this one, effectively allowing it to have a "negative" margin but without having to use any unsupported negative value.
Answered By - CommonsWare
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.