下面一段代码给大家分享Android 自定义TextView实现滑动解锁高亮文字效果,具体代码如下所示:

public class HightLightTextView extends TextView {
  // 存储view的宽度
  private int mTextViewWidth = 0;
  // 画笔
  private Paint mPaint;
  // 线性渲染
  private LinearGradient mLinearGradient;
  // 存储变换的matrix
  private Matrix matrix;
  // 移动距离
  private int mTranslateX = 0;
  // 构造方法
  public HightLightTextView(Context context) {
    this(context, null);
  }
  public HightLightTextView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }
  public HightLightTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }
  /**
   * view的调用过程:构造方法->onFinishInflate->onSizeChanged->onDraw
   */
  @Override
  protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    // 获取view的宽度,初始化画笔等初始属性
    if (mTextViewWidth == 0) {
      mTextViewWidth = getMeasuredWidth();
      // 如果宽度大于0的话,则初始化
      if (mTextViewWidth > 0) {
        // 初始化画笔
        mPaint = getPaint();
        // 线性渲染
        mLinearGradient = new LinearGradient(0, getMeasuredHeight(), mTextViewWidth, 0,
            new int[]{0X55FFFFFF, 0XFFFFFFFF, 0X55FFFFFF},
            new float[]{0, 0.5f, 1}, Shader.TileMode.CLAMP);
        mPaint.setShader(mLinearGradient);
        matrix = new Matrix();
      }
    }
  }
  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (matrix != null) {
      mTranslateX += mTextViewWidth / 10;
      // 如果移动的距离大于两倍的宽度,则重新开始移动
      if (mTranslateX > 2 * mTextViewWidth) {
        mTranslateX = -mTextViewWidth;
      }
      // 平移matrix
      matrix.setTranslate(mTranslateX, 0);
      // 设置线性变化的matrix
      mLinearGradient.setLocalMatrix(matrix);
      // 延迟50ms重绘 (重绘时会重新调用onDraw)
      postInvalidateDelayed(50);
    }
  }
}

补充:

Android TextView指定关键字高亮显示

项目中有这个需求,网上搜了一把,方法挺多的,这里选择一个简单的,已验证可用的方法,记录下,方便以后查阅。

TextView tv = (TextView) findViewById(R.id.hello);
SpannableString s = new SpannableString(getResources().getString(R.string.linkify));
Pattern p = Pattern.compile("abc");
Matcher m = p.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
s.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
tv.setText(s); 

很简单,tv就是TextView控件,s是要显示的字符串,“abc”是要高亮显示的关键字。

02-07 20:43