We can use single textview for:
1. Different textsizes.
2. Different colors.
3. Click event.
4. Linking with URL etc.
private void prepareStylishText ( TextView view ) {
SpannableStringBuilder spanTxt = new SpannableStringBuilder("Different");
//set the text clickable.
spanTxt.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Different style text in android.",
Toast.LENGTH_SHORT).show();
}
},
0, spanTxt.length(), 0 );
//set the text color.
spanTxt.setSpan(new ForegroundColorSpan(Color.RED),
0, spanTxt.length(), 0 );
//add more text.
spanTxt.append(" style");
spanTxt.setSpan(new ForegroundColorSpan(Color.BLUE),
spanTxt.length() - " style".length(), spanTxt.length(), 0 );
spanTxt.append(" text with single textview in");
spanTxt.setSpan(new ForegroundColorSpan(Color.BLACK),
spanTxt.length() - " text with single textview in".length(), spanTxt.length(), 0 );
spanTxt.append(" android.");
//make the textsize 2 times.
spanTxt.setSpan(new RelativeSizeSpan(2f), spanTxt.length() - " android".length(), spanTxt.length(), 0 );
//make the link.
spanTxt.setSpan(new URLSpan("http://developer.android.com/index.html"), spanTxt.length() - " android".length(), spanTxt.length(), 0 );
//set the color after the link else the link color will override it.
spanTxt.setSpan(new ForegroundColorSpan(Color.GREEN),
spanTxt.length() - " android".length(), spanTxt.length(), 0 );
//make click and url to work.
view.setMovementMethod(LinkMovementMethod.getInstance());
view.setText(spanTxt, BufferType.SPANNABLE);
}
Output:
No comments:
Post a Comment