GeorgeYang'Blog

my technology blog

自定义DynamicDrawableSpan将文字转成一块可同时删除

阅读:522 创建时间:17-03-07 09:45:30 tags:android

开发过程中,有时需要将#标签#归类为一块,在edittext中可以整块变色和删除,该方法类似编辑框中输入表情,表情是一串文字转成一个ImageSpan,ImageSpan继承DynamicDrawableSpan,所以写一个类似ImageSpan的继承DynamicDrawableSpan的TextImageSpan类

博客出处

 /**
  * 文字转成图片块,用于一次性删除一块文字
  * Created by george.yang on 17/3/7.
  */

 public class TextImageSpan extends DynamicDrawableSpan {
     private String mText;
     private Paint mPaint;
     private Drawable mDrawable;

     public TextImageSpan(String text, Paint paint) {
         this(text,paint,ALIGN_BOTTOM);
     }

     public TextImageSpan(String text, Paint paint, int verticalAlignment) {
         super(verticalAlignment);
         mText = text;
         mPaint = paint;

         int height =  Math.round(paint.measureText("口"));
         int width = Math.round(paint.measureText(mText));

         mDrawable = new ColorDrawable(Color.TRANSPARENT);
         mDrawable.setBounds(0, 0, width, height);
     }

     @Override
     public Drawable getDrawable() {
         return mDrawable;
     }

     @Override
     public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
         super.draw(canvas, text, start, end, x, top, y, bottom, paint);
         paint.setTypeface(mPaint.getTypeface());
         paint.setColor(mPaint.getColor());
         paint.setTextSize(mPaint.getTextSize());
         canvas.drawText(text.subSequence(start, end).toString(), x, y, paint);
     }
 }

用法如下:

 highLightPaint = new Paint();
 highLightPaint.setTypeface(Typeface.create("normal", Typeface.BOLD));
 highLightPaint.setTextSize(mEditText.getTextSize());
 highLightPaint.setColor(mEditText.getTextColors().getDefaultColor());


 SpannableString msp = new SpannableString(msg); 
 msp.setSpan(new TextImageSpan(text,highLightPaint));

 mEditText.setText(msp);