What is the difference between a View\'s Margin and Padding?
Padding is within the view, margin is outside. Padding is available for all views. Depending on the view, there may or may not be a visual difference between padding and margin.
For buttons, for example, the characteristic button background image includes the padding, but not the margin. In other words, adding more padding makes the button look visually bigger, while adding more margin just makes the gap between the button and the next control wider.
For TextView
s, on the other hand, the visual effect of padding and margin is identical.
Whether or not margin is available is determined by the container of the view, not by the view itself. In LinearLayout
margin is supported, in AbsoluteLayout
(considered obsolete now) - no.
In addition to all the correct answers above, one other difference is that padding increases the clickable area of a view, whereas margins do not. This is useful if you have a smallish clickable image but want to make the click handler forgiving.
For eg, see this image of my layout with an ImageView
(the Android icon) where I set the paddingBotton
to be 100dp
(the image is the stock launcher mipmap ic_launcher
). With the attached click handler I was able to click way outside and below the image and still register a click.
Sometimes you can achieve the same result by playing only with padding OR margin. Example :
Say View X contains view Y (aka : View Y is inside View X).
-View Y with Margin=30 OR View X with Padding=30 will achieve the same result: View Y will have an offset of 30.
Margin refers to the extra space outside of an element. Padding refers to the extra space within an element. The margin is the extra space around the control. The padding is extra space inside the control.
It's hard to see the difference with margin and padding with a white fill, but with a colored fill you can see it fine.
Padding is inside of a View.
Margin is outside of a View.
This difference may be relevant to background or size properties.
Padding is the space inside the border between the border and the actual image or cell contents. Margins are the spaces outside the border, between the border and the other elements next to this object.