Search code examples
androidkotlinandroid-recyclerviewsearchview

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


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.


Solution

  • 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.