1

In my android app i have to show tags on Textview. There can be multiple tag in same textView and i want to add click event to each tag. There may be some other text in same textview.How can i formate text in such a way all tags are clickable with bold text and other text as normal text. Suppose Text "#tag1 text message #tag2 #tag3 normal text" is to be set in text view with #tag1,#tag2 and #tag3 with bold text and remaining text with normal text style,so how can i achieve this.

Thanks in advance.

Larme
  • 24,190
  • 6
  • 51
  • 81
Ravi Bhandari
  • 4,682
  • 8
  • 40
  • 68

2 Answers2

3

You can use something like this,

String str = "<b> #tag1 </b> " + textMessage + "<b> #tag2  #tag3 </b>" + normalText; 
your_textview.setText(Html.fromHtml(str));

You can try SpannableStringBuilder also.

Aniruddha
  • 4,477
  • 2
  • 21
  • 39
0

You can try using SpannableStringBuilder

SpannableStringBuilder can:

  • Change Text Color
  • Multiple Click Actions etc

For code reference, you can check this post

private static void singleTextView(TextView textView, final String userName, String status, final String songName) {

    SpannableStringBuilder spanText = new SpannableStringBuilder();
    spanText.append(userName);
    spanText.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View widget) {

            // On Click Action

        }

        @Override
        public void updateDrawState(TextPaint textPaint) {
            textPaint.setColor(textPaint.linkColor);    // you can use custom color
            textPaint.setUnderlineText(false);    // this remove the underline
        }
    }, spanText.length() - userName.length(), spanText.length(), 0);

    spanText.append(status);
    spanText.append(songName);
    spanText.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View widget) {

            // On Click Action

        }

        @Override
        public void updateDrawState(TextPaint textPaint) {
            textPaint.setColor(textPaint.linkColor);    // you can use custom color
            textPaint.setUnderlineText(false);    // this remove the underline
        }
    },spanText.length() - songName.length(), spanText.length(), 0);

    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setText(spanText, TextView.BufferType.SPANNABLE);

}
Anurag Dhunna
  • 544
  • 1
  • 5
  • 17