Android控件篇 TextView限制文字长度且超过显示省略号

一、ellipsize

 <!-- Where to ellipsize text. 在哪里省略文本 -->
    <attr name="ellipsize">
        <enum name="none" value="0" />
        <enum name="start" value="1" />
        <enum name="middle" value="2" />
        <enum name="end" value="3" />
        <enum name="marquee" value="4" />
    </attr>

二、maxEms

 <!-- 使 TextView 最多有这么多 em 宽 -->
 <!-- Makes the TextView be at most this many ems wide. -->
        <attr name="maxEms" format="integer" min="0" />

三、singleLine

<!-- Constrains the text to a single horizontally scrolling line
     instead of letting it wrap onto multiple lines, and advances
     focus instead of inserting a newline when you press the
     enter key.

     The default value is false (multi-line wrapped text mode) for non-editable text, but if
     you specify any value for inputType, the default is true (single-line input field mode).

     {@deprecated This attribute is deprecated. Use <code>maxLines</code> instead to change
     the layout of a static text, and use the <code>textMultiLine</code> flag in the
     inputType attribute instead for editable text views (if both singleLine and inputType
     are supplied, the inputType flags will override the value of singleLine). } -->


     <attr name="singleLine" format="boolean" />

在这里插入图片描述

四、maxLength

<!-- 设置输入过滤器以将文本长度限制为指定数字 -->
<!-- Set an input filter to constrain the text length to the specified number. -->
        <attr name="maxLength" format="integer" min="0" />

五、使用

 <androidx.appcompat.widget.AppCompatTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end" 
        android:maxLength="10"
        android:maxEms="10"
        android:singleLine="true"
        android:text="欢迎关注彭老希,硬核干货持续更新!" />
Android开发中,TextView是用于显示文本的一个重要控件。当TextView上的文本超过控件的宽度时,可以通过一些属性和方法来处理这种情况。 一种常见的情况是,当文字长度超过TextView控件宽度时,会以省略号(...)的方式显示。这是通过在TextView中设置"android:ellipsize"属性来实现的。这个属性有几个可选值,其中"end"是最常用的,用于在末尾显示省略号。除了"end"之外,还有"start"(在开头显示省略号)、"middle"(在中间显示省略号)和"marquee"(以跑马灯的方式滚动显示文本)等可选值。 除了设置"android:ellipsize"属性外,还可以通过TextView的setMaxLines()方法来控制TextView最多显示的行数。当超过设置的行数时,同样会显示省略号。 另外,如果需要在代码中动态处理超过字符的情况,可以使用getText()方法获取TextView上的文本,然后通过判断文本的长度来处理。可以使用TextUtils类的ellipsize()方法,传入文本、TextView的宽度和省略号位置等参数,返回一个处理后的文本,再将其设置给TextView即可。 总之,Android中的TextView提供了多种处理超过字符的方式。可以通过设置"android:ellipsize"属性控制省略号的位置,使用setMaxLines()方法控制最大行数,或者通过代码动态处理文本长度,使用TextUtils类的ellipsize()方法来截取文本并添加省略号。这些方法可以根据具体的需求来选择和使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

其子昱舟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值