Align ImageView to the right with parent layout set to wrap_content

时间:2017-08-23 16:39:37

标签: android

I have a list of items in a horizontal recycler view, and a fairly simple item that should only have a TextView set to wrap_content and an ImageView that should be aligned to the right of the layout.

Theoretically I should be able to just set a layout_weight of 1 on the TextView, but that causes a random space to randomly show up sometimes in the view depending on where it is in the recycler view.

Is there anyway to align the close icon to the right, while still keeping the layout/textview width as wrap_content? The amount of text can vary quite a bit, so I can't actually set a fixed width. I'm fairly certain that I can't just set a layout_gravity of end on the ImageView since the parent layout's set to wrap_content.

See layout attached.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
android:background="@drawable/rounded_corners"
    android:minWidth="@dimen/min_width"
    android:maxWidth="@dimen/max_width"
    android:orientation="horizontal">

    <WPTextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:layout_weight="1"/>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical|end"/>
</LinearLayout>

2 个答案:

答案 0 :(得分:0)

在不知道项目应该是什么样子以及它需要如何表现的情况下,很难判断出你遇到的问题是什么。

如果图像只是文本右侧的小图像,您只需在文本视图中添加右图:

https://developer.android.com/reference/android/widget/TextView.html#attr_android:drawableRight

答案 1 :(得分:0)

如果您可以将LinearLayout替换为RelativeLayout,那么您可以使用

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
android:background="@drawable/rounded_corners"
    android:minWidth="@dimen/min_width"
    android:maxWidth="@dimen/max_width">

    <WPTextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>


    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/tv" />

</RelativeLayout>

TextViewImageView之间的间距可以通过边距进行调整。上述代码中使用的属性是不言自明的。