我有一个TextView,其中包含一个(可能很大)字符串,其中可能包含一个或多个“链接”。这些链接不是标准的“ www”。链接,但是他们将需要启动新的活动。如何获取一些较大的文本,对其进行扫描以查找以“ / r /”或“ r /”开头的单词,然后将这些单词更改为可点击的元素以启动活动?我怀疑我需要使用Linkify,但是在查看了一些示例之后,我仍然不清楚如何使用它。
以下是我需要转换为链接的文本的示例(请注意,加粗文本是需要转换为链接的文本):
某些具有 / r / some 链接的文本。此 r /文本可能具有许多 / r /许多链接。
答案 0 :(得分:0)
使用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()
中告诉他们的方式进行操作