简单代码实现TabLayout 条目的图文混排

来源:互联网 发布:电视剧全集获取源码 编辑:程序博客网 时间:2024/06/05 03:12

最近项目要实现类似的效果


用TabLayout加上Fragment实现,但是以前都是用的文字标题,现在有个图文的标题,然后就犯难了,然后就看Tab这个类是否有官方的方法,然后一看

确实是有,不过设置完以后一看:

尼玛是上下的关系,跟要求不符合啊 而且还不怎么美观,然后我就想tab的setText方法是不是textview的 然后用textView的setCompoundDrawablesWithIntrinsicBounds的方法设置,不过看了看方法和源码,并没有把TextView暴露出去,百度了一波,有人说可以用自定义布局可以实现,不过感觉有点大才小用,个人还是比较害怕麻烦,正好也采用了图文混排,所以是否可以用SpannableStringBuilder来实现呢?


一看这个setText()的方法,还可以传CharSequence,那这条路还是可以走通,然后就Duang Duang Duang 设置一通


设置完跑一跑吧,然后一看我擦!!

这是什么鬼,为什么不显示呢,然后又是一通百度然后说应该加上textAllCaps = false 这个属性才会起作用,因为默认是true,意思呢就是说除了文字别的都不现实,所以这么设置了没有效果,但是没有这个属相啊!!!只能曲线救国,通过style设置了,官方的一个style包含这个属性:


自定义一个style:


引用设置:


注意!注意!注意!

要用app:tabTextApperarance 这个属性引用自定义style 而不是style属性,否则也是无效果

跑一跑程序:


现在显示图片比字体大,看着美观,但是如果把图片设置小了的话就会...

难看的没法说了,百度了一下图片居中的ImageSpan然后找到一个:

public class VerticalImageSpan extends ImageSpan {    public VerticalImageSpan(Drawable drawable) {        super(drawable);    }    public int getSize(Paint paint, CharSequence text, int start, int end,                       Paint.FontMetricsInt fontMetricsInt) {        Drawable drawable = getDrawable();        Rect rect = drawable.getBounds();        if (fontMetricsInt != null) {            Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();            int fontHeight = fmPaint.bottom - fmPaint.top;            int drHeight = rect.bottom - rect.top;            //对于这里我表示,我不知道为啥是这样。不应该是fontHeight/2?但是只有fontHeight/4才能对齐            //难道是因为TextView的draw的时候top和bottom是大于实际的?具体请看下图            //所以fontHeight/4是去除偏差?            int top = drHeight / 2 - fontHeight / 4;            int bottom = drHeight / 2 + fontHeight / 4;            fontMetricsInt.ascent = -bottom;            fontMetricsInt.top = -bottom;            fontMetricsInt.bottom = top;            fontMetricsInt.descent = top;        }        return rect.right;    }    @Override    public void draw(Canvas canvas, CharSequence text, int start, int end,                     float x, int top, int y, int bottom, Paint paint) {        Drawable drawable = getDrawable();        canvas.save();        int transY = 0;        //获得将要显示的文本高度-图片高度除2等居中位置+top(换行情况)        transY = ((bottom - top) - drawable.getBounds().bottom) / 2 + top;        canvas.translate(x, transY);        drawable.draw(canvas);        canvas.restore();    }}
最后:

收工


原创粉丝点击