Monday, 2 December 2013

Clickable text in TextView + text bold + text color (ClickableSpan + Span bold color)

Here is short example how to use spannables.
My TextView was named "text_terms_link", so you should use your own view or rename like mine.

 ClickableSpan cs = new ClickableSpan() {  
   @Override  
   public void onClick(View view) {  
     //action stuff here  
   }  
 };  
 
 //getting text from xml = "Terms and Conditions"  
 String text_terms_string = getResources().getString(R.string.register_terms_text);  
 SpannableString ss = new SpannableString(text_terms_string);  
 
 //we need find oud position of "Terms" text: first index and the last  
 int termStart = text_terms_string.indexOf("Terms");  
 int termStop = termStart + "term".length();  
 
 //we set here clickable our text  
 ss.setSpan(cs, termStart, termStop, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  
 
 //we set here our color i.e. #cccccc in this example I take color from xml  
 ss.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.aquaBlue)),  
   termStart,termStop,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  
 
 //we set here text to be bolded    
 ss.setSpan(new StyleSpan(Typeface.BOLD),termStart,termStop,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  
 
 //I set here spannable text to my previous declared TextView  
 text_terms_link.setText(ss);  
 
 //We set here clickable text, this is important !!  
 text_terms_link.setMovementMethod(LinkMovementMethod.getInstance());