代码
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)
效果