Aligning a TextView and ImageView inside a LinearLayout

瘦欲@ 提交于 2019-12-10 20:47:21

问题


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?


回答1:


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"/>



回答2:


I think you try to use a RelativeLayout and using align parent right on the image and align parent left on the TextView.



来源:https://stackoverflow.com/questions/13112205/aligning-a-textview-and-imageview-inside-a-linearlayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!