【问题标题】:how to limit textView's width according to left width如何根据左侧宽度限制textView的宽度
【发布时间】:2018-10-03 12:57:52
【问题描述】:

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

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 的宽度吗?

【问题讨论】:

    标签: android android-layout textview truncate android-relativelayout


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • The easiest way is to just give the imageView a hard coded DP width and height, then set the text to 0 width with a weight of 1 inside a Linear Layout. 谢谢,但是当有足够的空间时,文本和图像会相距很远,我希望它们靠近
    • 您好 Elad,文本左对齐,因此没有空格。您还可以在 textView 上放置一个重量为 1 的布局包装器,以占用空间并将您的 textview 的重力浮动到您喜欢的任何地方。所以我对你的回答感到困惑。请详细说明您要完成的工作,因为将带有文本框的图像放在旁边,这是我为您提供的解决方案。你指的是什么“空间”?也许您处理图像不正确,也就是没有正确填充 imageView 空间。而且您希望漂浮在 imageView 未使用的空间上。那是不同的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    相关资源
    最近更新 更多