android - Higher order function for ClickableSpan
问题描述
I'm trying to capture the click on a textview with links. To achieve this:
- I created a BindingAdapter which has two params (a: TextView, clickListener: () -> Unit).
Inside the BindingAdapter:
val clickableSpan = object : ClickableSpan() { override fun onClick(widget: View) = onClickListener.invoke() } ```
In a ViewModel I created a
fun processUrl() { Code Here }
- In the layout.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.
Thanks in advance.
解决方案
您应该展开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){
}
推荐阅读
- r - Dplyr 将数据从开始和停止级别重塑为每周级别
- java - 如何强制 Java Socket 的 InputStream 抛出 IOException?
- c - 使用 Gcc 将 C 函数名称导出到带有特殊字符的 DLL/SO
- html - HTML 在新选项卡按钮中打开链接
- php - Laravel - How to optimize identical loops in blade views
- node.js - Gaxios - NodeJS - Spreadsheet Google 上的此文档不支持此操作
- c# - “异步任务”与“返回 Task.Run”
- python - 截断 f 字符串浮点数而不四舍五入
- sql - 为多个 id 插入多个值
- excel - 根据报告日期查找数据