Android:添加“内部"链接到TextView的一部分,该链接链接到我的代码中的操作 [英] Android: add "internal" links to part of a TextView, that links to action in my code
问题描述
正如标题所说明的,我想添加指向我的TextView
的链接,并附带以下两个警告:
As the title explains, I'd like to add links to my TextView
, with these two caveats:
-
我希望链接作用于
TextView
的一部分,而不是完整的链接(类似于HTML中的A
锚点).
I want the link to act on a part of the
TextView
, not the full one (something like anA
anchor in HTML).
我希望链接指向代码中的操作,而不是网站.我可以在自己的活动中定义一个方法,或者实现一个OnClickListener
,然后在单击该特定链接时执行该方法.
I want the link to point to an action in my code, not a website. I could define a method in my activity, or implement an OnClickListener
, and execute that when that specific link is clicked.
到目前为止,我已成功使用以下方法将电话号码,地址,网站和电子邮件转换为专用的外部链接:
So far, I succeeded to turn phone numbers, addresses, web sites and emails into dedicated external links using:
Linkify.addLinks(message, Linkify.ALL);
我想要内部链接(到我的方法)类似的东西,并且可以定义自定义链接.
I'd like something similar for internal links (to my method), with the possibility to define custom ones.
而且,使用带有内部链接和Web视图的网页并不是一个真正的选择,因为我已经定义了几个复杂的布局,并且不得不修改整个应用程序和概念会很痛苦...
Also, using a web page with internal link and a web view is not really an option, as I already have several complex layouts defined, and having to modify the whole application and concepts would be quite a pain...
有什么主意吗?
Kabuko给了我一个很好的解决方案,这正是我的实现方式:
Kabuko gave me a very good solution, here is exactly how I implemented it:
final TextView descriptionTextView = (TextView) findViewById(R.id.description);
final Spannable span = Spannable.Factory.getInstance().newSpannable("the full text for the view");
span.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(StartEventActivity.this, "LINK CLICKED", Toast.LENGTH_SHORT).show();
}
}, 1, 20, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // 1 and 20 to be replaced with actual index of start and end of the desired link
descriptionTextView.setText(span);
descriptionTextView.setMovementMethod(LinkMovementMethod.getInstance());
推荐答案
如果您想实际转到URL,则可以使用 ClickableSpan
.
If you wanted to actually go to URLs you could use Html.fromHtml
, but if you want your own click handlers you can use a ClickableSpan
.
这篇关于Android:添加“内部"链接到TextView的一部分,该链接链接到我的代码中的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!