首页 > 解决方案 > 如何根据左侧宽度限制textView的宽度

问题描述

我有一个布局(可以是相对的、线性的或约束的)

TextView 与父左对齐,然后 ImageView(固定宽度)从右对齐到 textView。

我希望先渲染图像,然后再渲染文本视图。

这意味着我希望在呈现图像后根据左侧空间截断文本视图。

  <RelativeLayout
      android:id="@+id/account_name_layout"
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:layout_weight="1"
      android:layout_marginBottom="@dimen/account_menu_account_name_layout_bottom_margin">
    <TextView
        android:id="@+id/account_name"
        style="@style/AccountDataAccountName"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:lines="1"
        android:ellipsize="end"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        tools:text="emailisverylongaswellwewantittogettruncated@gmail.longdomain.com"/>

    <ImageView
        android:id="@+id/account_name_chevron"
        android:layout_width="@dimen/account_menu_chevron_size"
        android:minWidth="@dimen/account_menu_chevron_size"
        android:layout_height="@dimen/account_menu_chevron_size"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/account_name"
        android:layout_marginTop="@dimen/account_menu_chevron_top_margin"
        android:layout_marginLeft="@dimen/account_menu_chevron_left_margin"/>
  </RelativeLayout>

我尝试了几个选项:

1)告诉文本留在图像视图

2)重视文本视图 - 两个元素之间的差距。

3) 将 minWidth 设置为图像视图 - 只是让 imageView 比例变小并没有帮助。

知道如何首先渲染图像以及如何根据左侧宽度限制 textView 的宽度吗?

标签: androidandroid-layouttextviewtruncateandroid-relativelayout

解决方案


您可以强制 imageView 的宽度。这将防止 textview 将其推离空间。如果您说您这样做了,请发布生成的图像,因为这没有任何意义。

你上面的例子没有相互限制,没有强制不覆盖或推开。您需要一些约束,例如“toTheLeftOf”或“Weight”或 LinearLayout 来强制执行它,因为 Weight 仅适用于 LinearLayout。

最简单的方法是给 imageView 一个硬编码的 DP 宽度和高度,然后在线性布局中将文本设置为 0 宽度,权重为 1。

如果需要,您还可以使用百分比,使用 LinearLayout 然后将权重总和设为 100(例如,表示 100%)。然后为您的图像分配它需要的任何百分比,例如 layout_weight=30 并给 textview 70。

这些选项中的任何一个都适合您。如果您尝试了它,但它没有,然后发布您尝试过的代码,因为它会起作用,除非您正在做一些在当前示例中不可见的愚蠢行为。正如我一直这样做的那样,每次你排成一行时,通常左边的图像固定,右边的文本增长。


推荐阅读