Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I center two TextViews vertically within a Layout

I have a RelativeLayout (that I am not married to) and two TextViews. I would like the bottom of the first TextView to line up with the center of it's parent, and the top of the second TextView to line up with the center of it's parent.

enter image description here

I put a green line in the picture above at the (vertical) center of the parent. The TextViews are currently in exactly the right spot, but I did this as I will describe below with margin's and aligning them to the parent and knowing the parent's size.

For various reasons I can't use just one TextView and center it. Also I don't know the height of the parent, so I can't align each to the top/bottom of the parent and margin them down/up to center them.

I also tried having another View that takes up half the height and be invisible, but layout_height doesn't take percents (or at least it gave me errors).

Any ideas how I can accomplish this?

Should I just put the two TextViews inside another layout and have that center itself?

like image 397
xbakesx Avatar asked Dec 19 '12 17:12

xbakesx


2 Answers

Create a 0-height view that is centered in its parent and serves as an anchor. (Use the attribute android:layout_centerVertical="true" for this.) Position one text view above the anchor and the other below the anchor.

like image 97
Ted Hopp Avatar answered Nov 05 '22 15:11

Ted Hopp


I've solved this problem before by using a vertical LinearLayout with the two TextViews inside it.

ps.: the Android Design Guidelines http://developer.android.com/design/patterns/pure-android.html specific points out to Don't use right-pointing carets on line items. It might not be a line item that you're doing, but in case it is, just to point it out.

like image 21
Budius Avatar answered Nov 05 '22 15:11

Budius