tags:

views:

391

answers:

1

My layout design is a TextView with long text and a ImageView to the right of the TextView. I want to center the ImageView in its parent vertically, so I used android:layout_centerVertical="true", but it turned out that the ImageView was aligned to the bottom of its parent. If I don't use layout_centerVertical property, the ImageView will be aligned to the top of its parent. How can I solve this problem? Thanks.

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:background="#000000">
    <ImageView android:id="@+id/t3" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:src="@drawable/arrow_right"
        android:layout_alignParentRight="true" android:background="#ff0000"
        android:layout_centerVertical="true" android:scaleType="centerInside" />
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This a very very very very very very very very very very very very very very very very long sentence"
        android:textColor="#231ACC" android:layout_toLeftOf="@id/t3" />
</RelativeLayout>
A: 

You could use a LinearLayout with layout_width and layout_height set to fill_parent and gravity set to vertical_center.

Something like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center_vertical|center_horizontal"
        android:orientation="horizontal">

        <EditText 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:id="@+id/input_field"
            android:gravity="left"
            android:layout_weight="1"
            android:text="Left Aligned"/>
               <EditText  
            android:id="@+id/input_field"
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:gravity="right"
            android:layout_weight="1"
            android:text="Right Aligned"/>
    </LinearLayout>
</LinearLayout>
jeremynealbrown
Could you post your XML file?
The code sample is from something I was working on a couple of days ago where I needed to horizontally and vertically center a row of text input fields. The task you describe sounds similar.
jeremynealbrown
In my example, it is different. I want the size of the ImageView to the right of the TextView to be exact the size of the picture the ImageView contains. So your example doesn't work for my case.