SpannableStringBuilder to create String with multiple fonts/text sizes etc Example?

后端 未结 9 1490
眼角桃花
眼角桃花 2020-11-28 03:00

I need to create a String placed in a TextView that will display a string like this:

First Part Not Bold BOLD rest not bold

9条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 03:49

    If you are using Kotlin you can do the following using the android-ktx library

    val s = SpannableStringBuilder()
            .append("First Part Not Bold ")
            .bold { append("BOLD") } 
            .append("Rest not bold")
    

    The bold is an extension function on SpannableStringBuilder. You can see the documentation here for a list of operations you can use.

    Another example:

    val s = SpannableStringBuilder()
                .color(green, { append("Green text ") })
                .append("Normal text ")
                .scale(0.5, { append("Text at half size " })
                .backgroundColor(green, { append("Background green") })
    

    Where green is a resolved RGB color.

    It is even possible to nest spans so you end up with an embedded DSL:

    bold { underline { italic { append("Bold and underlined") } } }
    

    You will need the following in your app module level build.gradle for it to work:

    repositories {
        google()
    }
    
    dependencies {
        implementation "androidx.core:core-ktx:1.2.0"
    }
    

提交回复
热议问题