我有这样的文字:“ SUV是最好的”。在此文本中,仅必须突出显示SUV,并且在单击SUV时必须将它们定向到某个网站。我该如何实现?

问候

最佳答案

需要使用Spannablestring和Click span选项来达到您的要求。

请尝试以下解决方案。

解决方案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"/>


爪哇

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);


解决方案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());


祝您编码愉快! :)

09-25 21:40