0

I have a text like "SUV are the best". In this piece of text, only SUV must be highlighted and on clicking SUV they must be directed to some website. How can I achieve this?

Regards

Community
  • 1
  • 1
The AV
  • 129
  • 2
  • 16

3 Answers3

1

Need to use the Spannablestring and Click span options to attain what you required.

Try the below solutions.

Solution 1 :

XML

<TextView
  android:layout_width = "wrap_content"
  android:layout_height = "wrap_content"
  android:textSize="24sp"
  android:textColor="#234356"
  android:padding="5dp"
  android:id = "@+id/testview"/>

JAVA

TextView test = (TextView) findViewById(R.id.testview);

SpannableString ss = new SpannableString("SUV is the Best. Offers Avail");
ClickableSpan clickableSpan = new ClickableSpan() {
  @Override
  public void onClick(View textView) {
    // open your browser here with the link
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setType("*/*");
    i.setData(Uri.parse("http://www.google.com")); // your link goes here don't forget to add http://
    startActivity(new Intent(Intent.createChooser(i, "Open website using")));
  }

  @Override
  public void updateDrawState(TextPaint ds) {
    super.updateDrawState(ds);
    ds.setUnderlineText(false);
  }
};
// 0 and 3 are the characters start and end where we need to open link on click here SUV
ss.setSpan(clickableSpan, 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
test.setText(ss);
test.setMovementMethod(LinkMovementMethod.getInstance());
test.setHighlightColor(Color.GREEN);

Solution 2:

TextView test = (TextView) findViewById(R.id.testview);
test.setText(Html.fromHtml("<a href=\"http://www.google.com\">SUV</a>  <b> is the Best. Offers Avail</b> "));
test.setMovementMethod(LinkMovementMethod.getInstance());

Happy coding..!! :)

Swaminathan V
  • 4,663
  • 2
  • 22
  • 32
0

In case you are talking about web, try this:

<p>Your text <a href="https://www.google.com" target="_blank>your link</a> some more text.</p>

Here you can find more information about anchor tags: https://developer.mozilla.org/en/docs/Web/HTML/Element/a

Nora
  • 3,093
  • 2
  • 20
  • 22
0

Can you add tags in between of text? If yes simply do like below:

<a href="your url">SUV</a> are the best

And if you want to linkify a text without adding the tag in between the text, you can use regex to do so.

Please follow this url for that:

Community
  • 1
  • 1
Aman Jain
  • 655
  • 5
  • 17