首页 > 系统 > Android > 正文

Android中实现词组高亮TextView方法示例

2019-12-12 01:47:07
字体:
来源:转载
供稿:网友

前言

本文主要给大家介绍了关于Android实现词组高亮TextView的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

HighlightTextView

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

特点

  • 文本高亮
  • 单词自动换行
  • 高亮词组保持在同一行显示


主要逻辑:

两个 Paint 负责绘制不同的文字

在每次绘制之前计算将要绘制的文本是否会超出屏幕宽度,如果超出则换行

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 (本地下载)

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对武林网的支持。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表