安卓:从点击文字发射活动文字

2023-09-12 01:08:12 作者:babypink

有没有什么方法可以让我从一个字符串的一部分推出的活动。

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());

基本上你有一个跨度对象附加到角色,你想点击的范围内。既然你反正使用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.

另外,您也可以定义一个只有自己知道的字符串中的标签。 即&LT;活性GT; 并提供自己的标记处理程序的Html.fromSource()方法。这样,你的TagHandler实例可以做这样的事情,围绕一个特定的颜色,下划线,加粗,使其可点击的标记文本。不过我只会推荐TagHandler方法,如果你发现自己写这种类型的codeA不少。

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.

 
精彩推荐
图片推荐