Android TextView实现词组高亮的示例代码

时间:2022-07-28
本文章向大家介绍Android TextView实现词组高亮的示例代码,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文介绍了Android TextView实现词组高亮的示例代码,分享给大家,具体如下:

HighlightTextView

Android文本高亮控件,基于View实现。

特点

  1. 文本高亮
  2. 单词自动换行
  3. 高亮词组保持在同一行显示

效果如下:

主要逻辑:

  1. 两个 Paint 负责绘制不同的文字
  2. 在每次绘制之前计算将要绘制的文本是否会超出屏幕宽度,如果超出则换行
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    float x_draw = getPaddingLeft();
    float y_draw = getPaddingTop() + dfPaint.getTextSize();
    for (ExtendText t : extendTexts) {
      Paint paint = t.isHighlight ? hlPaint : dfPaint;
      float textLen = paint.measureText(t.textUnit);
      if (x_draw + textLen   width) {
        x_draw = getPaddingLeft();
        y_draw += paint.getTextSize();
      }
      canvas.drawText(t.textUnit, x_draw, y_draw, paint);
      x_draw += textLen;
    }
  }

Demo

Java:

public class MainActivity extends Activity {
  private final static String TEXT = "";
  private final static String[] HIGHLIGHT = {};

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    HighLightTextView hlTv = (HighLightTextView) findViewById(R.id.hlTv);
    hlTv.setDisplayedText(TEXT, Arrays.asList(HIGHLIGHT));
    hlTv.setDefaultColor(Color.BLACK);
    hlTv.setHighlightColor(ContextCompat.getColor(this, R.color.colorPrimary));

  }
}

XML:

<com.jy.highlighttextview.HighLightTextView
  android:id="@+id/hlTv"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:padding="5dp"
  app:textSize="16sp" / 

Methods:

method 方法

description 描述

setDefaultColor(int color)

设置默认显示颜色

setHighlightColor(int color)

设置高亮颜色

setDisplayedText(String text, List<String highlights)

设置显示的文本和高亮词组

setTextSize(float size)

设置字体大小

xml value:

app:defaultColor="@color/colorPrimary"
app:highlightColor="@color/colorAccent"
app:text="@string/app_name"
app:textSize="16sp"

完整请移步github- jiyangg – HighlightText

以上就是本文的全部内容,希望对大家的学习有所帮助。