本文介紹了Android TextView實現詞組高亮的示例代碼,分享給大家,具體如下:
HighlightTextView
Android文本高亮控件,基于View實現。
特點
效果如下:

主要邏輯:
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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答