Android ClickableSpan get text onClick()

后端 未结 4 1867
陌清茗
陌清茗 2020-12-05 14:46

I\'m working on ClickableSpan in a TextView, and I\'m trying to get the clicked span\'s text. This is my code.

// this is the text we\'ll be ope         


        
4条回答
  •  情深已故
    2020-12-05 15:11

    Edited: previous code was wrong, this works

        // make "dolor" (characters 12 to 17) display a toast message when touched
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                TextView textView = (TextView) view;
                CharSequence charSequence = textView.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spannableText = (Spannable)charSequence;
                    ClickableSpan[] spans = spannableText.getSpans(0, textView.length(), ClickableSpan.class);
                    for (ClickableSpan span : spans) {
                        int start = spannableText.getSpanStart(span);
                        int end = spannableText.getSpanEnd(span);
                        Toast.makeText(MainActivity.this, charSequence.subSequence(start, end), Toast.LENGTH_LONG).show();
                    }
                }
            }
        };
    

提交回复
热议问题