做地图开发需求,有一个搜索关键字匹配的需求,需要做到关键字的匹配置蓝的操作
分享一下个人的思考,请各位大佬斧正
1.自定义TextView
Kotlin
class HighlightedTextView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {
private val TAG = "HighlightedTextView"
private var highlightColor = Color.BLUE
private var keywords: List<String> = emptyList()
private var textWords:String = "";
fun setKeywords(keywords: String,textWords:String) {
this.textWords = textWords;
this.keywords = keywords.toList().map { it.toString() }.toMutableList()
postInvalidate()
}
override fun onDraw(canvas: Canvas) {
val paint = paint
val originalColor = Color.BLACK
val lines = textWords.split("\n")
for (line in lines) {
val words = line.split("")
var x = 0f
for (word in words) {
if (keywords.any { word.contains(it, ignoreCase = true) }) {
paint.color = highlightColor
} else {
paint.color = originalColor
}
canvas.drawText(word , x, baseline.toFloat(), paint)
x += paint.measureText(word)
}
}
}
}
2.XML中调用
这里截取了部分,可以根据需求来修改
XML
<com.cariad.map.view.HighlightedTextView
android:id="@+id/item_search_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingRight="24dp"
android:textStyle="bold"
android:maxLines="1"
android:singleLine="true"
android:text="杭州西湖风景名胜区"
android:textColor="#000000"
android:textSize="28sp"
app:layout_constraintRight_toLeftOf="@id/item_search_result_send"
app:layout_constraintLeft_toRightOf="@id/item_search_marker_icon"
app:layout_constraintTop_toTopOf="parent">
</com.cariad.map.view.HighlightedTextView>
3.代码中调用
Kotlin
holder.searchResultName.setKeywords(keywords, result.poiItemV2.title)
4.最终效果