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
?
If a we want to set the gravity of content inside a view then we will use "android:gravity", and if we want to set the gravity of this view (as a whole) within its parent view then we will use "android:layout_gravity".
There is many difference in the
gravity
andlayout-gravity
. I am going to explain my experience about these 2 concepts(All information i got due to my observation and some websites).Note:-
Gravity is used inside the View Content as some User have answer and it is same for all
ViewGroup Layout
.Layout-gravity
is used with the parent View as some User have answer.Gravity and Layout-gravity
is work more useful with theFrameLayout
childs .We can't use Gravity and Layout-gravity
in FrameLayout's Tag ....We can set Child View any where in the
FrameLayout
usinglayout-gravity
.We can use every single value of gravity inside the FrameLayout (eg:-
center_vertical
,center_horizontal
,center
,top
, etc), but it is not possible with other ViewGroup Layouts .FrameLayout
fully working onLayout-gravity
. Example:- If you work onFrameLayout
then you don't need to change whole Layout for adding new View. You just add View as last in theFrameLayout
and give himLayout-gravity
with value.(This is adavantages of layout-gravity with FrameLayout).Output:-
Gravity
working same as above but here differnce is that we can use Gravity inside theLinearLayout View
andRelativeLayout View
which is not possible inFrameLayout View
.Note:- Here we can set only 3 values of
layout_gravity
that is (left
|right
|center
(also calledcenter_horizontal
)).Output:-
Note:- Here we can set also 3 values of
layout_gravity
that is (top
|bottom
|center
(also calledcenter_vertical
)).output:-
Note:- We can't use
layout_gravity
in theRelativeLayout Views
but we can usegravity
to setRelativeLayout
childs to same position....Something I saw on Sandip's blog that I almost missed, fixed my problem. He said
layout_gravity
DOES NOT WORK WITHLinearLayout
.If you're using a
LinearLayout
and the gravity settings are driving you nuts (like me), then switch to something else.I actually switched to a
RelativeLayout
then usedlayout_alignParentLeft
andlayout_alignParentRight
on the 2 containedTextView
s to get them on one line to go far left and far right.android:gravity
-> Sets the gravity of the content of the View its used on.android:layout_gravity
-> Sets the gravity of it's Parent's view or LayoutFrom what I can gather layout_gravity is the gravity of that view inside its parent, and gravity is the gravity of the children inside that view.
I think this is right but the best way to find out is to play around.
Look at the image to be clear about gravity