How do I center several views in an Android layout?
In my case I have two text views,开发者_如何转开发 I want them to be centered in my activity.
The problem is when I use:
android:gravity="center_vertical|center_horizontal"
android:layout_centerInParent="true"
The two text views are above each other and I'm using LinearLayout
as a parent.
You should remove the vertical and parent-based parts, and leave just the
android:gravity="center_horizontal"
for both of the TextViews
.
If it's enough, that the first TextView is centered vertically, then you can set it to |center_vertical
, and bind the second to this one with android:layout_below
.
If you need these text views to be exactly in the vertical center of the activity, then you should encapsulate them into an other (e.g. Linear)Layout with android:height="wrap_content"
and android:layout_centerInParent="true"
(in RelativeLayout
) or android:gravity="center_vertical|center_horizontal"
.
Try setting the Orientation property of the LinearLayout to "Horizontal":
<LinearLayout blah blah android:orientation="Horizontal"></LinearLayout>
Note : This tells the LinearLayout how you want the elements to stack, if you dont define this, then it will not stack them properly, refer to my diagram below for an explanation.
When you set this property it will have the elements be right next to eachother.
Horizontal
[x][x]
Vertical
[x]
[x]
Another thing to keep in mind is that all you should need to do to center elements in a linear layout is this:
<LinearLayout blah blah android:gravity="center"></LinearLayout>
if this doesn't work try this:
<LinearLayout blah blah android:layout_gravity="center"></LinearLayout>
its definitely a good idea to know the difference, but I'm not going to look it up for you.
android:layout_centerInParent="true"
is only valid for a RelativeLayout
.
精彩评论