diff --git a/src/androidTest/java/androidx/core/text/SpannableStringBuilderTest.kt b/src/androidTest/java/androidx/core/text/SpannableStringBuilderTest.kt index c66dd1fc..8769eb83 100644 --- a/src/androidTest/java/androidx/core/text/SpannableStringBuilderTest.kt +++ b/src/androidTest/java/androidx/core/text/SpannableStringBuilderTest.kt @@ -29,6 +29,7 @@ import android.text.style.StrikethroughSpan import android.text.style.StyleSpan import android.text.style.SubscriptSpan import android.text.style.SuperscriptSpan +import android.text.style.URLSpan import android.text.style.UnderlineSpan import org.junit.Assert.assertEquals import org.junit.Assert.assertSame @@ -115,6 +116,24 @@ class SpannableStringBuilderTest { assertEquals(12, result.getSpanEnd(underline)) } + @Test fun builderURL() { + val result: SpannedString = buildSpannedString { + append("Hello, ") + url("https://www.google.com") { + append("World") + } + } + assertEquals("Hello, World", result.toString()) + + val spans = result.getSpans() + assertEquals(1, spans.size) + + val url = spans.filterIsInstance().single() + assertEquals("https://www.google.com", url.url) + assertEquals(7, result.getSpanStart(url)) + assertEquals(12, result.getSpanEnd(url)) + } + @Test fun builderColor() { val result: SpannedString = buildSpannedString { append("Hello, ") diff --git a/src/main/java/androidx/core/text/SpannableStringBuilder.kt b/src/main/java/androidx/core/text/SpannableStringBuilder.kt index e49ccd26..f0b205d8 100644 --- a/src/main/java/androidx/core/text/SpannableStringBuilder.kt +++ b/src/main/java/androidx/core/text/SpannableStringBuilder.kt @@ -28,6 +28,7 @@ import android.text.style.StrikethroughSpan import android.text.style.StyleSpan import android.text.style.SubscriptSpan import android.text.style.SuperscriptSpan +import android.text.style.URLSpan import android.text.style.UnderlineSpan import androidx.annotation.ColorInt @@ -99,6 +100,16 @@ inline fun SpannableStringBuilder.italic(builderAction: SpannableStringBuilder.( inline fun SpannableStringBuilder.underline(builderAction: SpannableStringBuilder.() -> Unit) = inSpans(UnderlineSpan(), builderAction = builderAction) +/** + * Wrap appended text in [builderAction] in an [URLSpan]. + * + * @see SpannableStringBuilder.inSpans + */ +inline fun SpannableStringBuilder.url( + url: String, + builderAction: SpannableStringBuilder.() -> Unit +) = inSpans(URLSpan(url), builderAction = builderAction) + /** * Wrap appended text in [builderAction] in a [ForegroundColorSpan]. *