【问题标题】:Convert text within a TextView into links that start an activity将 TextView 中的文本转换为启动活动的链接
【发布时间】:2019-04-11 12:28:49
【问题描述】:

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

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

一些具有 /r/some 链接的文本。此 r/text 可能有许多 /r/many 链接。

【问题讨论】:

    标签: android textview android-textattributes


    【解决方案1】:

    使用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() 中告诉他们的操作进行操作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-03
      • 2011-05-18
      • 2023-03-18
      • 2011-10-18
      • 1970-01-01
      • 2013-07-27
      • 1970-01-01
      • 2012-10-18
      相关资源
      最近更新 更多