Android TextView實現(xiàn)詞組高亮的示例代碼
本文介紹了Android TextView實現(xiàn)詞組高亮的示例代碼,分享給大家,具體如下:
HighlightTextView
Android文本高亮控件,基于View實現(xiàn)。
特點
- 文本高亮
- 單詞自動換行
- 高亮詞組保持在同一行顯示
效果如下:

主要邏輯:
- 兩個 Paint 負(fù)責(zé)繪制不同的文字
- 在每次繪制之前計算將要繪制的文本是否會超出屏幕寬度,如果超出則換行
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) | 設(shè)置默認(rèn)顯示顏色 |
| setHighlightColor(int color) | 設(shè)置高亮顏色 |
| setDisplayedText(String text, List<String> highlights) | 設(shè)置顯示的文本和高亮詞組 |
| setTextSize(float size) | 設(shè)置字體大小 |
xml value:
app:defaultColor="@color/colorPrimary" app:highlightColor="@color/colorAccent" app:text="@string/app_name" app:textSize="16sp"
完整請移步github-> jiyangg -> HighlightText
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android自定義View實現(xiàn)通訊錄字母索引(仿微信通訊錄)
本文主要介紹了Android自定義View實現(xiàn)通訊錄字母索引(仿微信通訊錄)的實現(xiàn)步驟與方法,具有很好的參考價值,下面跟著小編一起來看下吧2016-12-12
Android中ScrollView監(jiān)聽滑動距離案例講解
這篇文章主要介紹了Android中ScrollView監(jiān)聽滑動距離案例講解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
解決Android 5.1限制外置SD卡寫入權(quán)限的問題
今天小編就為大家分享一篇解決Android 5.1限制外置SD卡寫入權(quán)限的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
Android自定義ViewGroup實現(xiàn)朋友圈九宮格控件
在我們的實際應(yīng)用中,經(jīng)常需要用到自定義控件,比如自定義圓形頭像,自定義計步器等等,這篇文章主要給大家介紹了關(guān)于Android自定義ViewGroup實現(xiàn)朋友圈九宮格控件的相關(guān)資料,需要的朋友可以參考下2021-07-07
android實現(xiàn)圖片驗證碼方法解析(自繪控件)
本文主要介紹了android自繪控件的應(yīng)用--實現(xiàn)圖片驗證碼方法案例,具有一定的參考價值,下面跟著小編一起來看下吧2017-01-01
Android使用Sensor感應(yīng)器獲取用戶移動方向(指南針原理)
這篇文章主要介紹了Android使用Sensor感應(yīng)器獲取用戶移動方向的方法,實例分析了指南針原理極其應(yīng)用,需要的朋友可以參考下2015-12-12

