简体   繁体   中英

Center view to another in RelativeLayout

I have two views that I want to center vertically in a RelativeLayout.

Is there a way to do this without using gravity/layout_gravity ? 在此输入图像描述

My problem behind this question :

I need to do a layout with several squares and under each one a TextView. The main problem is that the TextViews must overlap. Only one TextView will be visible at a time. Each TextView has a different lengh.

I started with a RelativeLayout but encountred the previous problem. And I can't group the views 2 per 2 because I need to set a layout_toRightOf of the previous square.

在此输入图像描述

Current layout :

For the moment, I have set a magic number in layout_marginLeft for each square (to the border of the parent view) but it isn't clean at all.

在此输入图像描述

Thanks

Use android:layout_centerInParent="true" to center something into a RelativeLayout
You can use android:layout_below="@id/your_first_view" to put your second View below the first !
If you want to do more complex stuff you may separate your different Views and store the into new LinearLayout that you set to horizontal or vertical depending on your needs.
Another trick can be to create empty Views with small height or width and that can help you to position thing around them !
This combined to the toRightOf toLeftOf stuff will do what you want

Finaly, I kept the the layout_marginLeft but I put the values in my res/values/dimens.xml, it is cleaner and I can have a dimens.xml per screen dimension. A trick is to set the width of the textViews deliberately big so it won't depend on the strings lenght.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM