开发者

How to center align a view?

开发者 https://www.devze.com 2023-03-12 05:45 出处:网络
I need to lay a variable number of views (may just be one) next to each other like in LinearLayout. But I want the whole arrangement to be center aligned. The views should be next to each other. But t

I need to lay a variable number of views (may just be one) next to each other like in LinearLayout. But I want the whole arrangement to be center aligned. The views should be next to each other. But the whole arrangement shou开发者_如何学Gold be equidistant from the left and right edge of the screen or the containing parent. How can I accomplish this?


You will have to wrap your views inside a 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 use android:layout_width="wrap_content". If you are working with RelativeLayout, it will be:

<RelativeLayout>
    <LinearLayout
       android:layout_width="wrap_content"
       android:layout_centerHorizontal="true">
       <View/>
       <View/>
       <View/>
    </LinearLayout>
</RelativeLayout>


Did you try

      android:gravity="center" 

?


This will do it for you

android:layout_gravity="center_horizontal"

Also you want to consider the weight property to make sure that this layout element takes priority 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消