Search code examples
javaandroidstringkotlinspannablestring

How to set different color & size for numbers and characters of a string


I receive a dynamic string from a web service and it contains numbers and characters.

Examples

Distance is 5000 mph

Arrival in 2 hours & 40 minutes


I want a different color - fontype - size for both the numbers and the charcters. I know how to use Spannable for a string, but I must know the start and end index for each which I don't because the string is dynamic.!

Is there a way to achieve this?


Solution

  • Here you can use the below code to find out all the numbers from your string in an array and by using it you can customize it-

    private fun getNumbers(string:String){
            val p = Pattern.compile("-?\\d+(,\\d+)*?\\.?\\d+?")
            val numbers: MutableList<String> = ArrayList()
            val m: Matcher =
                p.matcher(string)
            while (m.find()) {
                numbers.add(m.group())
    
            }
            println(numbers)
        }
    

    If the string is Arrival in 2 hours & 40 minutes then this function will return you - [2,40] as the end result.