Home > Software design >  How to edit List<String> in RecyclerView like change Color and remove or replace character?
How to edit List<String> in RecyclerView like change Color and remove or replace character?

Time:01-10

How to edit String and List in RecyclerView in Kotlin for:
1- Change color for all numbers.
2- remove custom signs (example: , ;).

1- for color numbers I tried this but not working in list:

private fun digitsStyle() {
        var txt = getString(R.string.text)
        "\\d ".toRegex().findAll(txt)
            .flatMap { it.groupValues }
            .forEach {
                txt = txt.replace(it, "<font color=red>$it</font>")
            }
        text.text = Html.fromHtml(txt)
    }

2- for remove signs I tried this but also not working in list:

fun replaceSign(tv: TextView) {
        var string = getString(R.string.text).replace(",", "")
            .replace(";", "").replace("'", "")
        tv.text = string
    }

CodePudding user response:

I recommend you separate out your Regex processing from the view logic so you can more easily reason and test it.

The problem with the first code is that you not approach replacement in the correct way (in particular the txt = txt.... part).

The Regex class provides a convenience method for exactly what you want to do: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/-regex/replace.html but notice you need to define a capture group, i.e. add (..) and notice in the replacement expression $1 this is reference to the first capturing group.

Here is working code

import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test

    fun markUpNumbersInRed(src: String) = Regex("(\\d )").replace(src, "<font color=red>$1</font>")

    @Test
    fun markUpNumbersInRedTest() {
        markUpNumbersInRed("1 abc 2 def 3") shouldBe
                "<font color=red>1</font> abc <font color=red>2</font> def <font color=red>3</font>"
        markUpNumbersInRed("abc") shouldBe "abc"
    }

You can use the same Regex.replace approach for your second use case, use something like ([,';])

CodePudding user response:

For replace or remove you can use regrex expression

"12A.&f'".replace("[^A-Za-z0-9 ]"..toRegex(), "") //12Af

And for Color you can use

 var stringToFilter = "A122AAAA.2-b3_4C"
 val stringWithOnlyDigits = stringToFilter.map {  if(it.isDigit())"<font color=red>$it</font>"  else it}
 println(stringWithOnlyDigits.joinToString("")) //A<font color=red>1</font><font color=red>2</font><font color=red>2</font>AAAA.<font color=red>2</font>-b<font color=red>3</font>_<font color=red>4</font>C
  • Related