给TextView添加一个标签

代码


fun TextView.addTag(content:String=" ",tag:String=" ",@DrawableRes tagBgId:Int=android.R.drawable.ic_secure,tagColor:Int=android.R.color.holo_red_dark,tagTextSize: Float=12F,bottomPadding:Int=2){

    val totalContent =content.plus(" ").plus(if (tag.isEmpty()) " " else tag)
    val layout= LinearLayout(this.context)
    val tagView = if (tag.isEmpty()) ImageView(this.context).apply {
        setImageResource(tagBgId)
        setPadding(0,0,0,this.context.dp2px(dpValue = bottomPadding))

    } else TextView(this.context).apply {
        text =tag
        background =ResourcesCompat.getDrawable(this.context.resources,tagBgId,null)
        textSize =tagTextSize
        setTextColor(ResourcesCompat.getColor(this.context.resources,tagColor,null))
        includeFontPadding =false
        setPadding(this.context.dp2px(dpValue = 2),0,this.context.dp2px(dpValue =2),this.context.dp2px(dpValue = bottomPadding))
        height=this.context.dp2px(dpValue = 16)
        gravity =Gravity.CENTER
    }

    val layoutParams =LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)
    layout.addView(tagView,layoutParams)
    layout.measure(View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED),View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED))
    layout.layout(0,0,tagView.measuredWidth,tagView.measuredHeight)
    layout.setPadding(this.context.dp2px(dpValue = 20),0,0,0)

    val bitmap =Bitmap.createBitmap(tagView.width,tagView.height,Bitmap.Config.ARGB_8888)
    val canvas =Canvas(bitmap)
    tagView.draw(canvas)

    val imageSpan =ImageSpan(this.context,bitmap)
    val ssb =SpannableStringBuilder(totalContent)
    ssb.setSpan(imageSpan,content.length+1,totalContent.length,Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
    this.text =ssb

}

用法

 mBinding.tv.addTag(content = getString(R.string.app_name), tag = "复制", tagBgId = R.drawable.bg_text_view_tag, tagColor = R.color.colorAccent)
 
 mBinding.tv2.addTag(content = getString(R.string.app_name).plus(other = "添加图片标签添加图片标签添加图片标签添加图片标签添加图片标签添加图片标签添加图片标签添加图片标签"), tagBgId = R.mipmap.img_copy)

效果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值