Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

Android: Launch activity from clickable text

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

eg I have this in my strings.xml file:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this,

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...