自定义TextView折叠文本

项目需求:

某折扣字符串:“满10减30·满20减30·满30减30·满40减40·满50减30·满60减30·满70减30·满80减30·满90减40·满100减30”
如果将上述文案使用maxline:1 和ellipsize:end 显示到一行中,显示如下:
在满60减30的时候因为放不下,被折叠起来了。
在这里插入图片描述
现产品要求如下:
在这里插入图片描述
也就是说:当在某单条折扣(如满60减30)已经放不下一行的时候,就要获取到上一个能放下的折扣(以点做区分)此案例中满60减30放不下,他的上一条折扣是满50减30,因此就展示到此即可。

方案:
  1. 获取到被折叠的位置
  2. 根据折叠位置,索引到上一条折扣
实现:
@SuppressLint("AppCompatCustomView")
class MeasureTextView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : TextView(context, attrs, defStyleAttr) {
    
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //1. 获取到折叠位置
        val ellipsisStart = layout.getEllipsisStart(0)
        if(ellipsisStart>0){
            //2.获取到截取之前的文本
            text = text?.substring(0,ellipsisStart)
            //3.索引到上一条折扣文本
            val lastIndexOf = text?.lastIndexOf("·")
            if(lastIndexOf!=-1){
                //4.获取到最终需要的文本
                text = lastIndexOf?.let { text?.substring(0, it) }
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Android自定义TextView中显示全部内容,可以使用以下两种方法: 1. 使用setEllipsize()方法 通过设置setEllipsize()方法,可以在TextView的末尾添加省略号,从而指示文本被截断。你可以使用以下代码来实现: ``` yourTextView.setEllipsize(TextUtils.TruncateAt.END); yourTextView.setSingleLine(true); ``` 上述代码将设置TextView只显示一行并在末尾添加省略号。 2. 自定义TextView 你可以从TextView类继承一个新类,并覆盖onMeasure()方法以测量控件的高度和宽度。 你可以使用以下代码实现: ``` public class CustomTextView extends TextView { public CustomTextView(Context context) { super(context); } public CustomTextView(Context context, AttributeSet attrs) { super(context, attrs); } public CustomTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //获取TextView的内容 CharSequence text = getText(); if (text != null) { //测量TextView的高度 int width = getMeasuredWidth(); int height = getMeasuredHeight(); int lineCount = getLineCount(); int lineHeight = getLineHeight(); int totalHeight = lineCount * lineHeight; if (totalHeight > height) { setMeasuredDimension(width, totalHeight); } } } } ``` 上述代码将测量TextView的高度,如果文本的高度超出了TextView的高度,则调整TextView的高度以适应文本。然后你可以使用此自定义TextView来显示你的文本

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值