How to center a View inside of an Android Layout?

2019-01-16 11:10发布

I want to put a layout in the center of the screen.

9条回答
家丑人穷心不美
2楼-- · 2019-01-16 11:27

I was able to center a view using

android:layout_centerHorizontal="true" 

and

android:layout_centerVertical="true" 

params.

查看更多
SAY GOODBYE
3楼-- · 2019-01-16 11:38

If you want to center one view, use this one. In this case TextView must be the lowermost view in your XML because it's layout_height is match_parent.

<TextView 
    android:id="@+id/tv_to_be_centered"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:gravity="center"
    android:text="Some text"
/>
查看更多
The star\"
4楼-- · 2019-01-16 11:38

Updated answer: Constraint Layout

It seems that the trend in Android now is to use a Constraint layout. Although it is simple enough to center a view using a RelativeLayout (as other answers have shown), the ConstraintLayout is more powerful than the RelativeLayout for more complex layouts. So it is worth learning how do do now.

To center a view, just drag the handles to all four sides of the parent.

enter image description here

查看更多
登录 后发表回答