Android:从可点击文本启动活动 [英] Android: Launch activity from clickable text

查看:21
本文介绍了Android:从可点击文本启动活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以从字符串的一部分启动活动.

Is there any way I can launch an activity from a portion of a string.

例如我的 strings.xml 文件中有这个:

eg I have this in my strings.xml file:

<string name="clickable_string">This is a <u>clickable string</u></string>

我希望 u 标记之间的文本带有下划线,并在插入到 TextView

I would like the text between the u tags to be underlined and launch an activity when clicked when inserted in to a TextView

推荐答案

试试这个,

final Context context = ... // whereever your context is
CharSequence sequence = Html.fromSource(context.getString(R.string.clickable_string));
SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
UnderlineSpan[] underlines = strBuilder.getSpans(UnderlineSpan.class);
for(UnderlineSpan span : underlines) {
   int start = strBuilder.getSpanStart(span);
   int end = strBuilder.getSpanEnd(span);
   int flags = strBuilder.getSpanFlags(span);
   ClickableSpan myActivityLauncher = new ClickableSpan() {
     public void onClick(View view) {
       context.startActivity(getIntentForActivityToStart());
     }
   };

   strBuilder.setSpan(myActivityLauncher, start, end, flags);
}

TextView textView = ...
textView.setText(strBuilder);
textView.setMovementMethod(LinkMovementMethod.getInstance());

基本上,您必须将 Span 对象附加到您希望可点击的字符范围.由于您无论如何都在使用 HTML,因此您可以使用 Html.fromSource() 放置的下划线跨度作为您自己的跨度的标记.

Basically you have to attach a Span object to the range of characters you want to be clickable. Since you are using HTML anyways, you can use the underline spans placed by the Html.fromSource() as markers for your own spans.

或者,您也可以在只有您知道的字符串中定义一个标签.即 并将您自己的标记处理程序提供给 Html.fromSource() 方法.通过这种方式,您的 TagHandler 实例可以执行类似操作,用特定颜色、下划线、粗体围绕标记文本并使其可点击.但是,如果您发现自己经常编写此类代码,我只会推荐 TagHandler 方法.

Alternatively you could also define a Tag within the string that only you know of. i.e. <activity> And supply your own tag handler to the Html.fromSource() method. This way your TagHandler instance could do something like, surround the tagged text with a specific color, underline, bold and make it clickable. However I would only recommend the TagHandler approach if you find yourself writing this type of code a lot.

这篇关于Android:从可点击文本启动活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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