问题
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