-2

我有一个 TextView,其中包含一个(可能很大)字符串,该字符串可能包含一个或多个“链接”。这些链接不是标准的“www”。链接,而是他们需要启动一项新活动。如何获取一些大文本,扫描以“/r/”或“r/”开头的单词,然后将这些单词更改为可启动活动的可点击元素?我怀疑我需要使用Linkify,但是在查看了一些示例之后,我仍然不清楚如何使用它。

以下是我需要转换为链接的文本示例(注意粗体文本是需要转换为链接的部分):

一些具有/r/some链接的文本。这个r/text可能有很多/r/many链接。

4

1 回答 1

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

于 2018-11-08T01:50:34.487 回答