Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Align one element below and in the middle of another

I have an ImageView and TextView. I want to place the TextView below the image view but with the middle of the TextView aligned with the middle of the ImageView (along the horizontal axis). If the text in the TextView changes to something much larger or smaller, the middle of the text always needs to remain aligned with the middle of the ImageView. Is this possible in xml?

like image 737
Johann Avatar asked Jun 25 '12 06:06

Johann


1 Answers

Yes, you are simply looking to contain both elements in a vertical LinearLayout which has android:gravity set to center_horizontal.

Something like this:

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

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ... />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        ... />

</LinearLayout>

Because the TextView's width is wrap_content, setting its gravity shouldn't be necessary. I would do it just for safety (and additionally, I may set the width to match_parent as well).

like image 123
Cat Avatar answered Oct 19 '22 06:10

Cat