Aligning a TextView and ImageView inside a LinearLayout

android, android-linearlayout, imageview, textview, xml

Solution

RelativeLayout should solve your problem nicely using `android:layout_alignParentRight` and `android:layout_alignParentLeft`. Something like:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<TextView
    android:id="@+id/txtCategoryName"
    android:layout_alignParentLeft="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:singleLine="true"
    android:ellipsize="end"
    android:gravity="center_vertical"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:textColor="@color/list_text_color"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<ImageView
    android:id="@+id/imgArrowRight"
    android:layout_alignParentRight="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/right_arrow_44"
    android:contentDescription="@string/img_description_right_arrow"/>

Problem

I have a ListView with custom adapter and a layout for items in this List. The layout for the items is just a TextView with an ImageView. The image should be aligned to the right side of the screen. However, the image's position is shifting a bit, depending on the length of the text in the TextView. This is what it looks like: This is my XML code: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:gravity="center_vertical" > <TextView android:id="@+id/txtCategoryName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="10" android:singleLine="true" android:ellipsize="end" android:gravity="center_vertical" android:paddingTop="5dp" android:paddingBottom="5dp" android:textColor="@color/list_text_color" android:textAppearance="?android:attr/textAppearanceLarge" /> <ImageView android:id="@+id/imgArrowRight" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:src="@drawable/right_arrow_44" android:contentDescription="@string/img_description_right_arrow" android:layout_gravity="right" /> </LinearLayout> ``` How can I make the image be always aligned to the right, without being nudged?

Original source