简体   繁体   中英

ClickableSpan and HTML spanned in the same TextVeiw

I am attempting to implement a clickablespan in an existing HTML string in the view. The string already has href's where needed (excluding the span of characters that need to be handled programmatically). The HTML links are working as expected.

An example string:

<string name="terms_short">Message and data rates may apply. Message frequency varies. Contact customer service at <a href="tel:5555555555">(555) 555-5555</a> or via email <a href="mailto:cust_email_addr">Spiffy Email</a>. View our <a href="http://privacy_policy">Privacy Policy</a> and Terms and Conditions.</string>

In this example, displaying the HTML programmatically with clickable links is rather straight forward.

val terms = getString(R.string.terms_short)
binding.textView.text = HtmlCompat.fromHtml(terms, HtmlCompat.FROM_HTML_MODE_COMPACT)
binding.textView.movementMethod = LinkMovementMethod.getInstance()

Now, I need to add a ClickableSpan to be handled internally for Terms and Conditions . The terms are delivered within a dialog locally. I have been attempting to resolve this by getting the Spanned HTML into a string builder then adding an additional ClickableSpan however this tends to stop the existing url spans function. This results in dropping the HTML links and adding only the ClickableSpan

Here is what I last attempted:

<string name="terms_conditions">Terms and Conditions</string>
// -----------

val terms = getString(R.string.terms_short)
val sequence = HtmlCompat.fromHtml(terms, HtmlCompat.FROM_HTML_MODE_COMPACT)
val strBuilder = SpannableStringBuilder(sequence)

val termsString = getString(R.string.terms_conditions)

strBuilder.setSpan(
    object : ClickableSpan() {
        override fun onClick(widget: View) {
            Timber.d("Click handled internally")
        }
    },
    sequence.indexOf(termsString),
    sequence.indexOf(termsString) + termsString.length,
    SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
)

binding.textView.text = strBuilder
binding.textView.movementMethod = LinkMovementMethod.getInstance()

The linking didnt work due to getString() stripping the html tags out of the string. The HTML was working as expected prior because the resource was defined in the layout property not programmatically as shown here.

<string name="terms_short"><![CDATA[ Message and data rates may apply. Message frequency varies. Contact customer service at <a href="tel:5555555555">(555) 555-5555</a> or via email <a href="mailto:cust_email_addr">Spiffy Email</a>. View our <a href="http://privacy_policy">Privacy Policy</a> and Terms and Conditions.]]></string>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM