Last active
September 15, 2022 07:34
-
-
Save ercnksgl/58f9f7429be896427821c50a728f10a5 to your computer and use it in GitHub Desktop.
Text customizer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.text.Spanned | |
import androidx.core.text.HtmlCompat | |
class TextCustomizer { | |
class Builder(private val allText: String) { | |
private val parts = arrayListOf<Pair<String, Customize>>() | |
fun addTextToReplace(part: String, customize: Customize)= apply { | |
parts.add(Pair(part, customize)) | |
} | |
fun addListToReplace(items: List<Pair<String, Customize>>) = apply { | |
parts.addAll(items) | |
} | |
fun apply(): Spanned { | |
var result = allText | |
parts.map { part -> | |
var text = part.first | |
if (part.second.isItalic) text = String.format("<i>%s</i>", text) | |
if (part.second.isBold) text = String.format("<b>%s</b>", text) | |
if (part.second.isUnderline) text = String.format("<u>%s</u>", text) | |
part.second.hexColor?.let { | |
text = String.format("<font color='${part.second.hexColor}'>%s</font>", text) | |
} | |
result = result.replace(part.first, text) | |
} | |
return HtmlCompat.fromHtml(result, HtmlCompat.FROM_HTML_MODE_COMPACT) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment