[Android]TextView图文混排对齐

发布时间:2019-06-22 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[Android]TextView图文混排对齐脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
package com.chargerlink.app.ui.charging.panel.comment;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.style.ImageSpan;
import java.lang.ref.WeakReference;

/**
 * 图片垂直居中显示
 * Created by liuguoquan on 16/9/5.
 */
public class CenterImageSpan extends ImageSpan {

  private WeakReference<Drawable> mDrawableRef;

  public CenterImageSpan(Context context, int resourceId, int verticalAlignment) {
    super(context, resourceId, verticalAlignment);
  }

  @Override 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.descent - fmPaint.ascent;
      int drHeight = rect.bottom - rect.top;
      int centerY = fmPaint.ascent + fontHeight / 2;

      fontMetricsInt.ascent = centerY - drHeight / 2;
      fontMetricsInt.top = fontMetricsInt.ascent;
      fontMetricsInt.bottom = centerY + drHeight / 2;
      fontMetricsInt.descent = fontMetricsInt.bottom;
    }
    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 = getCachedDrawable();
    canvas.save();
    Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
    int fontHeight = fmPaint.descent - fmPaint.ascent;
    int centerY = y + fmPaint.descent - fontHeight / 2;
    int transY = centerY - (drawable.getBounds().bottom - drawable.getBounds().top) / 2;
    canvas.translate(x, transY);
    drawable.draw(canvas);
    canvas.restore();
  }

  private Drawable getCachedDrawable() {
    WeakReference<Drawable> wr = mDrawableRef;
    Drawable d = null;
    if (wr != null) {
      d = wr.get();
    }

    if (d == null) {
      d = getDrawable();
      mDrawableRef = new WeakReference<>(d);
    }

    return d;
  }
}

// 评论内容,设置标签、链接跳转
Spannable content = new SpannableStringBuilder("占位  " + comment.getContent());
CenterImageSpan span = new CenterImageSpan(mActivity,R.drawable.ic_btn_ask,ImageSpan.ALIGN_BASELINE);
// 用ImageSpan替换文本
content.setSpan(span, 0, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
holder.mAskText.setText(content);

脚本宝典总结

以上是脚本宝典为你收集整理的[Android]TextView图文混排对齐全部内容,希望文章能够帮你解决[Android]TextView图文混排对齐所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。