简体   繁体   中英

Align ImageView to center of a TextView in RelativeLayout

I have a Relative Layout as below:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_weight="0.38"
    android:background="@drawable/layout"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:layout_marginLeft="80dp"
        android:textColor="@color/text1color"
        android:textSize="15sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/text2"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/text1"
        android:layout_below="@+id/text1"
        android:background="@drawable/text2_background"
        android:layout_marginTop="10dp"
        android:paddingLeft="10dp"
        android:textColor="@color/text2color"
        android:textSize="13sp" />

    <com.widgets.CustomImageView
        android:id="@+id/myImage"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_margin="0dp"
        android:layout_alignParentBottom="true"
        android:layout_toLeftOf="@+id/text2"
        android:src="@drawable/logo" />

</RelativeLayout>

The ImageView @+id/myImage needs to align to the center of @+id/text2 TextView! Currently, it is aligning to the top of @+id/text2 and is aligning to the layout's parentBottom . I don't want this hack.

Is there a way of aligning the ImageView to the TextView 's center ?

This is a perfect case for a compound drawable (which is a best practice, to flatten your design).
The ImageView goes INSIDE the TextView text2, at its bottom:

Just add this to your text2 definition:

android:drawableBottom="@drawable/logo"

You can add some padding, too

android:drawablePadding="4dp"

The image is horizontally aligned to its container.
If the text grows vertically, the image will be pulled down (as the TextView grows).

To have the image left aligned and vertically centered, just change drawableTop with drawableLeft and you're done:

android:drawableLeft="@drawable/logo"

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