Sometimes we need to create a textview with 2 separate links or we need to show different colors in different parts of the same textview. In a normal textview we cant implement it directly. In order to attain this we using spannable textviews. In this we splitting text in to different parts and implement the different changes. Take an example below.
Textview mCommentTxt = (TextView) findViewById(R.id.contentTxt); MovementMethod m = holder.mCommentTxt.getMovementMethod(); if ((m == null) || !(m instanceof LinkMovementMethod)) { holder.mCommentTxt.setMovementMethod(LinkMovementMethod.getInstance()); } String content = String .format("##%s## checked-in $$%s$$", "username" ,"values"); mCommentTxt.setText(content); CharSequence txt = holder.mCommentTxt.getText(); String bgColor = "#E6E6E6"; txt = setSpanBetweenTokens(txt, "##", new ForegroundColorSpan(Color.parseColor(bgColor)), new BackgroundColorSpan(Color.parseColor(bgColor)), new ClickableSpan() { @Override public void onClick(View v) { // Onclick listner } @Override public void updateDrawState(TextPaint ds) { ds.setColor(Color.parseColor("#4866a3")); ds.setUnderlineText(false);// set to false to remove underline ds.setTypeface(Typeface.DEFAULT_BOLD); } }); txt = setSpanBetweenTokens(txt, "$$", new ForegroundColorSpan(Color.WHITE ), new BackgroundColorSpan(Color.parseColor(bgColor)),new ClickableSpan() { @Override public void onClick(View v) { // Onclick listener } @Override public void updateDrawState(TextPaint ds) { ds.setColor(Color.parseColor("#4866a3")); ds.setUnderlineText(false); // set to false to remove underline ds.setTypeface(Typeface.DEFAULT_BOLD); } }); mCommentTxt.setText( txt );
public static CharSequence setSpanBetweenTokens(CharSequence text, String token, CharacterStyle... cs) { int tokenLen = token.length(); int start = text.toString().indexOf(token) + tokenLen; int end = text.toString().indexOf(token, start); if (start > -1 && end > -1) { SpannableStringBuilder ssb = new SpannableStringBuilder(text); for (CharacterStyle c : cs){ ssb.setSpan(c, start, end, 0); } ssb.delete(end, end + tokenLen); ssb.delete(start - tokenLen, start); text = ssb; } return text; }
This comment has been removed by the author.
ReplyDelete