I know we can set the following values to the android:gravity
and android:layout_gravity
properties:
center
center_vertical
center_horizontal
, etc.
But I am confused regarding both of these.
What is the difference between the usage of android:gravity
and android:layout_gravity
?
Inside - Outside
gravity
arranges the content inside the view.layout_gravity
arranges the view's position outside of itself.Sometimes it helps to see a picture, too. The green and blue are
TextViews
and the other two background colors areLinearLayouts
.Notes
layout_gravity
does not work for views in aRelativeLayout
. Use it for views in aLinearLayout
orFrameLayout
. See my supplemental answer for more details.gravity
won't have any effect. Thus,wrap_content
andgravity
are meaningless together.layout_gravity
won't have any effect. Thus,match_parent
andlayout_gravity
are meaningless together.layout_gravity=center
looks the same aslayout_gravity=center_horizontal
here because they are in a vertical linear layout. You can't center vertically in this case, solayout_gravity=center
only centers horizontally.gravity
andlayout_gravity
on the views within a layout. To see what happens when you set thegravity
of the of the parent layout itself, check out the supplemental answer that I referred to above. (Summary:gravity
doesn't work well on aRelativeLayout
but can be useful with aLinearLayout
.)So remember, layout_gravity arranges a view in its layout. Gravity arranges the content inside the view.
xml
Here is the xml for the above image for your reference:
Related
The basic difference between the two is that-
android:gravity is used for child elements of the view.
android:layout_gravity is used for this element with respect to parent view.
is used to adjust for content of the view relative to its specify position (allocated area).
android:gravity="left"
would not do anything iflayout_width
is equal to the"wrap_content"
is used for view itself relative to the parent or layout file.
Their names should help you:
android:gravity
sets the gravity of the contents (i.e. it's subviews) of theView
it's used on.android:layout_gravity
sets the gravity of theView
orLayout
relative to its parent.And an example is here.
Just thought I'd add my own explanation here - coming from a background on iOS, this is how I've internalized the two in iOS terms: "Layout Gravity" affects your position in the superview. "Gravity" affects the position of your subviews within you. Said another way, Layout Gravity positions you yourself while gravity positions your children.
gravity--Applies to its own view.
layout-gravity---Applies to view related to its parent.