怎么在Android中利用TextView实现词组高亮

发布时间:2021-04-08 17:07:19 作者:Leah
来源:亿速云 阅读:145

这篇文章将为大家详细讲解有关怎么在Android中利用TextView实现词组高亮,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

HighlightTextView

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

特点

怎么在Android中利用TextView实现词组高亮

主要逻辑:

两个 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"

关于怎么在Android中利用TextView实现词组高亮就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. 怎么在Android中利用TextView实现超链接
  2. Android中怎么通过自定义TextView实现滑动解锁高亮文字

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android textview

上一篇:使用JavaScript怎么封装一个ajax功能函数

下一篇:怎么在Android中调用WebService

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》