简体   繁体   English

ClickableSpan 的高阶 function

[英]Higher order function for ClickableSpan

I'm trying to capture the click on a textview with links.我正在尝试通过链接捕获对 textview 的点击。 To achieve this:为达到这个:

  • I created a BindingAdapter which has two params (a: TextView, clickListener: () -> Unit).我创建了一个 BindingAdapter,它有两个参数(a:TextView,clickListener: () -> Unit)。
  • Inside the BindingAdapter:在 BindingAdapter 内部:

    •  val clickableSpan = object: ClickableSpan() { override fun onClick(widget: View) = onClickListener.invoke() } ```
  • In a ViewModel I created a fun processUrl() { Code Here }在 ViewModel 中,我创建了一个fun processUrl() { Code Here }

  • In the layout.xml:在布局中。xml:
    • <TextView app:infowithlinks="@{() -> model.processUrl()}"

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.一切正常,我希望当我单击 TextView 上的链接时,能够将 Url 发送到 ViewModel 内的 function。

Thanks in advance.提前致谢。

You should expand the onClickListener to accept the String.您应该展开onClickListener以接受字符串。 Then invoke it with argument.然后用参数调用它。

  @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)
               }
            }
        }  
        //....

    }

On the xml you'll have在 xml 上,您将拥有

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

And in the view model并在视图中 model

fun processUrl(url : String){

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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