使用ClickableSpan
. 以下是如何跨越文本的示例:
String text = "Some very nice text here. CLICKME. Don't click me.";
String word = "CLICKME";
// when user clicks that word it opens an activity
SpannableStringBuilder ssb = new SpannableStringBuilder(text);
int position = text.indexOf(word); // find the position of word in text
int length = word.length(); // length of the span, just for convenience
ClickableSpan mySpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
Intent mIntent = new Intent(this, SecondActivity.class);
startActivity(mIntent);
}
};
ssb.setSpan(mySpan, position, (position+length), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// setSpan needs 4 things: a Span object, beginning of the span, end of span, and
// and a modifier, which for now you can just c&p
TextView txtView = findViewById(R.id.txt);
txtView.setClickable(true);
txtView.setMovementMethod(LinkMovementMethod.getInstance());
// dont delete this last line. Without it, clicks aren't registered
txtView.setText(ssb);
您可以在文本中的不同位置设置多个跨度,它们都会按照您的指示进行操作onClick()