欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ImageSpan图片和在行文字居中

程序员文章站 2022-05-25 21:30:02
...

文字中添加图标:

/** 文字中增加图标 */
    public static Spannable addDrawableInText(int start, int end, int resouceId, Spannable text) {
        Drawable drawable = SkinManager.getInstance().getDrawable(resouceId);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        text.setSpan(new MyImageSpan(drawable), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return text;
    }

图片span

public class MyImageSpan extends ImageSpan {
    public MyImageSpan(Context arg0, int arg1) {
        super(arg0, arg1);
    }

    public MyImageSpan(Drawable d) {
        super(d);
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end,
                     float x, int top, int y, int bottom, Paint paint) {

        Drawable b = getDrawable();
        // font metrics of text to be replaced
        Paint.FontMetricsInt fm = paint.getFontMetricsInt();
        int transY = (y + fm.descent + y + fm.ascent) / 2
                - b.getBounds().bottom / 2;

        canvas.save();
        canvas.translate(x, transY);
        b.draw(canvas);
        canvas.restore();
    }
}

点击和颜色的span:

class TopicsBlueSpan extends ClickableSpan {
    private String content;

    public TopicsBlueSpan(String content) {
        this.content = content;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        ds.setColor(Color.BLUE);
        ds.setUnderlineText(false);
    }

    @Override
    public void onClick(View widget) {
        ...
    }
}

此时点击后会出现文字选中出现淡绿色的背景色现象。ds.setColor()设定的是span超链接的文本颜色,而不是点击后的颜色,点击后的背景颜色HighLightColor属于TextView的属性,通过方法
textview.setHighlightColor(Color.TRANSPARENT);解决。