Skip to content
This repository has been archived by the owner on Nov 14, 2018. It is now read-only.

Add url spanning #596

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<Any>()
assertEquals(1, spans.size)

val url = spans.filterIsInstance<URLSpan>().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, ")
Expand Down
11 changes: 11 additions & 0 deletions src/main/java/androidx/core/text/SpannableStringBuilder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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].
*
Expand Down