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

I have ImageView and TextView . I want to place a TextView below the image, 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 larger or smaller, the middle of the text should always be aligned with the middle of the ImageView . Is this possible in xml ?

+6
source share
3 answers

Yes, you just want to contain both elements in a vertical LinearLayout with android:gravity set to center_horizontal .

Something like that:

 <?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> 

Since the width of the TextView wrap_content , setting its gravity is not required. I would do this just for security (and besides, I can set the width also on match_parent ).

+6
source

set TextView android:layout_width="fill_parent" and set android:gravity="center" in TextView .

I think this will help you.

thanks

0
source

You can use RealtiveLayout as follows.

 <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" ... > <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" ... /> <TextView android:layout_below="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" /> </RelativeLayout> 

If you want your text view to have only one line, add the following properties to the TextView

Android: ellipsezed = "end" android: SingleLine = "true"

Use this layout and add it to any existing layout that you get the result you are looking for.

Hope this explanation works for you.

0
source

Source: https://habr.com/ru/post/918915/


All Articles