使用maxLength结束带有3个点的TextView

Yan*_*niv 51 android textview android-layout ellipsize

我的布局中有一个TextView,它是layout_width中的wrap_content.它最多限制为15个字符,所以我使用的是maxLength.

我需要用3个点(...)结束这个TextView,只有当我用dp给layout_width一个固定的大小时才会发生这种情况,这是我不想做的事情.

我知道有可能通过代码并在第15个字符后剪切字符串然后添加3个点,但我更喜欢用XML来做.

知道如何用3个点结束文本并留下wrap_content吗?

<TextView
        android:id="@+id/inbox_contactName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:lines="1"
        android:maxLines="1"
        android:ellipsize="end"
        android:singleLine="true"
        android:maxLength="15"
        android:textColor="#0670b4"
        android:textSize="16sp" />
Run Code Online (Sandbox Code Playgroud)

Kir*_*irk 69

这将解决您的问题,ellipsize在XML代码中使用属性

android:ellipsize="end" <!-- This makes the magic ... thing -->
android:maxEms="15" <!-- Limit of the Text -->
android:singleLine="true" <!-- In case if you want everything in one line -->
Run Code Online (Sandbox Code Playgroud)

编辑: singleLine弃用.请maxlines="1"改用.

  • @Kirk maxEms不能用于限制位数,而使用maxLength则不显示点. (3认同)
  • @king可能已弃用.在回答这个问题时,这是一个有效的解决方案.如果有人知道最新的补丁,请更新我的答案. (2认同)

Rav*_*avi 17

我收集(来自评论)@Yaniv已经使用代码解决了它 - 但这是正确的方法(使用xml).可以帮助其他在此登陆的用户.伎俩是使用宽容 torightof.

<RelativeLayout>
...
 <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:singleLine="true"
        android:layout_toRightOf="@id/some_element1"
        android:layout_toLeftOf="@id/some_element2"/>
...
<RelativeLayout>
Run Code Online (Sandbox Code Playgroud)


AZ_*_*AZ_ 11

您不能同时使用它们maxLength,Ellipsize虽然您可以定义,但Maximum EMS请参阅下面的示例

<TextView
        android:id="@+id/tv_hist_source_lang"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxEms="8"
        android:maxLines="1"
        android:text="TextView"
        android:textAppearance="?android:attr/textAppearanceMedium" />
Run Code Online (Sandbox Code Playgroud)

看起来像这样


Zho*_*gbo 10

您可以使用

android:maxWidth="100dp"
android:maxLines="1"
android:ellipsize="end"
Run Code Online (Sandbox Code Playgroud)

只有这对我有用.


Enz*_*kie 6

最简单的方法之一是添加Right Padding + Ellipsize

<TextView
            android:id="@+id/txtvw_contentcell_subhead"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Polem sampler, Lorem Ipsum golep tolem burop yemit noski"
            android:ellipsize="end"
            android:maxLines="1"
            android:textColor="@color/caption_black_color"
            android:textSize="@dimen/caption_size"
            android:paddingRight="40dp"/>
Run Code Online (Sandbox Code Playgroud)

这是一个带有字符限制的字幕文本示例。 在此处输入图片说明


Mah*_*him 5

用这个 android:ellipsize="end"