前言
在开发过程中,TextView中会出现一些特殊内容(如:部分内容颜色、字体、大小不同,并且部分字体可点击),写多个TextView又会显得麻烦,那又怎么解决这个问题呢?首页我们来看看TextView的源码,在android.text.style包下,有很多Span类,那么我们可以使用SpannableStringBuilder来设置Span,先看看实现效果:
使用方式:
val builder = SpannableStringUtil.create(context!!)
.setText("类似于HTML中的<li>标签的圆点效果")
.setBullet(android.R.color.holo_green_dark)//添加圆点
.setTextColor(android.R.color.black)
.setText("\n设置文字左侧显示引用样式")
.setQuote(android.R.color.holo_green_dark)
.setText("\n设置下划线以及删除线")
.setTextUnderline()//下划线
.setTextStrikeThrough()//删除线
.setTextColor(android.R.color.holo_red_dark)
.setTextSize(20)
.setTextStyle(Typeface.ITALIC)
.setText("这个可以点击")
.setTextColor(android.R.color.holo_green_dark)
.setTextSize(21)
.setTextStyle(Typeface.BOLD)//字体样式
.setClick(tv_span1,{
Log.e("data", it)
},true)//设置点击
.setText("这里设置下标")
.setTextColor(android.R.color.holo_blue_dark)
.setTextSubscript(6)//下标
.setTextColor(android.R.color.holo_orange_dark)
.setText("这里可以设置上标")
.setScaleX(1.5f)
.setTextColor(android.R.color.holo_green_dark)
.setTextSuperscript(6)//上标
.setTextColor(android.R.color.holo_blue_dark)
.setDrawable(R.mipmap.ic_launcher,100,100)
.setAlign(Layout.Alignment.ALIGN_OPPOSITE)
.build()
tv_span1.text = builder
val builder1 = SpannableStringUtil.create(context!!)
.setText("人的一生,有许多事情,是需要放在心里慢慢回味的,过去的就莫要追悔,一切向前看吧 任何打击都不足以成为你堕落的借口,即使你改变不了这个世界,你却依然可以改变自己,选择条正确的路永远走下去。")
.setTextColor(android