Android的可点击的TextView如何进行多次点击区域上的文字和捕捉区域选择 [英] Android Clickable TextView How To Make Multiple Click Regions on Text And Catch Region Selection

查看:171
本文介绍了Android的可点击的TextView如何进行多次点击区域上的文字和捕捉区域选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使文本的几个部分分别点击,例如在下面的文本:

I want to make several parts of text individually clickable for example in the text below:

获取FORCAST有一天,天气两日,七的日子。

Get the weather forcast one day, two day, seven day.

我希望能够点击的文字单独三个不同的区域来获得某一天,一日二,7天FORCAST。我不希望这转到一个网页的URL,但正好赶上上所显示的TextView活动内的文本区域的点击。

I want to be able to click individually three different regions of the text to get one day, two day or seven day forcast. I don't want this to goto a web page URL but just catch the click on the region of text inside the activity that is showing the TextView.

推荐答案

您应该能够完成,使用<一个href="http://developer.android.com/reference/android/text/style/ClickableSpan.html"><$c$c>ClickableSpan.基本上你需要创建一个 SpannableStringBuilder ,追加文本部分,并设置不同的ClickableSpan为每个点击的文本部分。

You should be able to accomplish that using ClickableSpan. Basically you need to create a SpannableStringBuilder, append the text parts and set a different ClickableSpan for each clickable text part.

SpannableStringBuilder sb = new SpannableStringBuilder();
String regularText = "This text is ";
String clickableText = "clickable";
sb.append(regularText);
sb.append(clickableText);
sb.setSpan(new ClickableSpan(), sb.length()-clickableText.length(), sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView tv = ...
tv.setText(sb);

这只是说明如何设置一个ClickableSpan一个例子。很显然,这会更有意义上面做一个循环,并设置了新的跨越与每个迭代。

This is just an example illustrating how to set a single ClickableSpan. Obviously it will make more sense to do above in a loop and set a new span with each iteration.

然而,由于ClickableSpan是一个抽象类,您首​​先需要将其与自己的具体实现扩展。更具体地说,onClick的方法将需要实施处理点击事件。

However, since ClickableSpan is an abstract class, you'll first need to extend it with your own concrete implementation. More specifically, the onClick method will need to be implemented to handle click events.

另外,不要忘了一个MovementMethod设置为TextView的,例如: LinkMovementMethod:

Also, don't forget to set a MovementMethod to the TextView, e.g. LinkMovementMethod:

tv.setMovementMethod(LinkMovementMethod.getInstance());

这篇关于Android的可点击的TextView如何进行多次点击区域上的文字和捕捉区域选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆