前言
本文主要給大家介紹了關于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/107381.html">android/75297.html">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 (本地下載)
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答