首页 > 解决方案 > Higher order function for ClickableSpan

问题描述

I'm trying to capture the click on a textview with links. To achieve this:

All that works well, I would like when I click the link on the TextView be able to send the Url to the function inside the ViewModel.

Thanks in advance.

标签: androidkotlinandroid-databindingkotlin-android-extensions

解决方案


您应该展开onClickListener以接受字符串。然后用参数调用它。

  @BindingAdapter("infowithlinks")
    fun TextView.setOnSpanClickListener(clickListener:Function1<String, Unit>){
        val clickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View){
              with(text as SpannableString) {
                val clickableSpan = getSpans<ClickableSpan>()
                    .first() // probably search correct one
                val start = getSpanStart(clickableSpan)
                val end = getSpanEnd(clickableSpan)
                val url = text.subSequence(start, end).toString()
                clickListener(url)
               }
            }
        }  
        //....

    }

在 xml 你将拥有

<TextView app:infowithlinks="@{model.processUrl}"

在视图模型中

fun processUrl(url : String){

}

推荐阅读