The SpannableString in android is a powerful way to beautify and manipulate different part of a simple text.
What is SpannableString?
This is the class for text whose content is immutable but to which markup objects can be attached and detached.
This implies that for a immutable content/string , we can provide different markup objects like URLSpan, ForegroundColorSpan, RelativeSizeSpan, ImageSpan, BackgroundColorSpan , ClickableSpan etc.
How to manipulate only a part of string by using SpannableString?
It is same as how it is done in the web
1. Creating a ClickableSpan
1 2 3 4 5 6 7 8 9 10 11 |
ClickableSpan clickableSpan = new ClickableSpan() { @Override public void onClick(View textView) { perfomClickAction(); } @Override public void updateDrawState(TextPaint textPaint) { super.updateDrawState(textPaint); } }; |
2. Creating a SpannableString
1 2 3 |
SpannableString spannableString = new SpannableString("YOUR STRING WITH CLICK"); spannableString.setSpan(clickableSpan, starting position of span, ending position of span, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); |
This will set the click action to a particular portion of the text.
3. Setting SpannableString to TextView
1 2 |
resendSmsTV = (TextView) findViewById(R.id.resend_sms); resendSmsTV.setText(spannableString); |