This article mainly introduces the implementation of Android in TextView to add multiple clickable text, can achieve similar to Android social software display points like the user and through the user name to enter the user's homepage function, is very practical skills, the need for friends can refer to the next. Specific as follows:
Most of the time we use social software to more or less like other people's posts, as shown in:
You can see that the user page shows just the name of the user who likes it, and clicking on those names can go to the user's homepage. Let's do a similar effect here.
The specific code is as follows:
1 @Override2 protected voidonCreate (Bundle savedinstancestate) {3 Super. OnCreate (savedinstancestate);4 Setcontentview (R.layout.activity_main); 5 6TextView Mtextview =(TextView) Rootview.findviewbyid (R.ID.LIKE_TV);7 8 //constructs multiple hyperlinks of HTML, with the selected location to get the user name9StringBuilder Sbbuilder =NewStringBuilder ();Ten for(inti = 0; I < 10; i++) { OneSbbuilder.append ("username-" + i + ","); A } - -String likeusers = sbbuilder.substring (0, Sbbuilder.lastindexof (",") . toString (); the Mtextview.setmovementmethod (Linkmovementmethod.getinstance ()); - Mtextview.settext (Addclickablepart (likeusers), buffertype.spannable); - - } + /** - * @paramStr + * @return A */ at Privatespannablestringbuilder Addclickablepart (String str) { - //first likes icon -Imagespan span =NewImagespan (Getactivity (), r.drawable.umeng_comm_like); -Spannablestring Spanstr =NewSpannablestring ("P.")); -Spanstr.setspan (span, 0, 1, spannable.span_inclusive_exclusive); - inSpannablestringbuilder SSB =NewSpannablestringbuilder (SPANSTR); - ssb.append (str); to +string[] Likeusers = Str.split (","); - the if(Likeusers.length > 0) { * //last one $ for(inti = 0; i < likeusers.length; i++) { Panax Notoginseng FinalString name =Likeusers[i]; - Final intStart = Str.indexof (name) +spanstr.length (); theSsb.setspan (NewClickablespan () { + A @Override the Public voidOnClick (View widget) { + Toast.maketext (GetView (). GetContext (), name, - toast.length_short). Show (); $ } $ - @Override - Public voidupdatedrawstate (textpaint ds) { the Super. Updatedrawstate (DS); - //Ds.setcolor (color.red);//Set Text colorWuyi //Remove the Underline theDs.setunderlinetext (false); - } Wu -}, start, start + name.length (), 0); About } $ } - returnSsb.append ("et") -+ Likeusers.length + "personally liked you."); -}//End of Addclickablepart
The effect is as follows:
Hopefully this article will help you with Android programming.
Add multiple clickable text to TextView in Android