How to center the alignment of a view?

I need to lay a variable number of views (there can be only one) next to each other, as in LinearLayout. But I want the whole arrangement to be centered. The views should be next to each other. But the whole layout should be equidistant from the left and right edges of the screen or containing the parent. How can i do this?

+8
android android-layout
source share
3 answers

You will need to wrap your views inside LinearLayout and your linear layout inside something else:

 <LinearLayout android:orientation="vertical"> <LinearLayout android:layout_width="wrap_content" android:layout_gravity="center_horizontal"> <View/> <View/> etc... </LinearLayout> </LinearLayout> 

Make sure all your views are used by android:layout_width="wrap_content" . If you are working with RelativeLayout , this will be:

 <RelativeLayout> <LinearLayout android:layout_width="wrap_content" android:layout_centerHorizontal="true"> <View/> <View/> <View/> </LinearLayout> </RelativeLayout> 
+18
source share

You tried

  android:gravity="center" 

?

+8
source share

It will do it for you

Android: layout_gravity = "center_horizontal"

You also want to consider the weight property to make sure that this layout element takes precedence over others.

http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html

To group everything together, you can use a frame layout or relative layout.

+2
source share

All Articles