How can we have searched characters colored when we use searchview in recyclerview?

笑着哭i 提交于 2020-04-24 07:54:09

问题


I have a recyclerview and I want to search in it with help of searchview. I want my searched characters to be colored and be specific.

I am programming with Kotlin.


回答1:


After a hard effort I found the answer myself. I use a function like this:

fun colorsearch(a:String,charText: String):SpannableStringBuilder{
    var l = 0
    var b:ArrayList<Int>
    b = ArrayList()
    var w = 0
    var i = 0
    if (charText!=""){
        label@ while (i < a.length) {
            var j=0
            while (j<charText.length){
                Log.v("abc", j.toString())
                if (i == a.length)
                    break@label
                while ((a[i] != charText[j])) {
                    if (j != 0) {
                        continue@label
                    }
                    i++
                    if (i == a.length)
                        break@label
                }
                i++
                j++
            }
            b.add(i)
            w++
            if (i == a.length)
                break@label
        }
    }

    val searchtitle = SpannableStringBuilder(a)
    while (l < w) {
        searchtitle.setSpan(
            ForegroundColorSpan(Color.RED),
            b[l] - charText.length, b[l],
            Spanned.SPAN_EXCLUSIVE_INCLUSIVE
        )
        l++
    }
    return searchtitle
}

The "charText" in "a" will be Red.



来源:https://stackoverflow.com/questions/59628149/how-can-we-have-searched-characters-colored-when-we-use-searchview-in-recyclervi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!