Format TextView to look like link

前端 未结 7 1614
醉话见心
醉话见心 2021-01-04 02:21

I\'ve been using the android:autoLink just fine for formatting links and such, but I need to use android:onClick so I can\'t use that in this case.

7条回答
  •  我在风中等你
    2021-01-04 02:56

    This is the shortest solution:

    final CharSequence text = tv.getText();
    final SpannableString spannableString = new SpannableString( text );
    spannableString.setSpan(new URLSpan(""), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    tv.setText(spannableString, TextView.BufferType.SPANNABLE);
    

    Sadly, the effect of clicking doesn't show up as being clicked on a real url link, but you can overcome it like so:

        final CharSequence text = tv.getText();
        final SpannableString notClickedString = new SpannableString(text);
        notClickedString.setSpan(new URLSpan(""), 0, notClickedString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(notClickedString, TextView.BufferType.SPANNABLE);
        final SpannableString clickedString = new SpannableString(notClickedString);
        clickedString.setSpan(new BackgroundColorSpan(Color.GRAY), 0, notClickedString.length(),
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(final View v, final MotionEvent event) {
                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    tv.setText(clickedString);
                    break;
                case MotionEvent.ACTION_UP:
                    tv.setText(notClickedString, TextView.BufferType.SPANNABLE);
                    v.performClick();
                    break;
                case MotionEvent.ACTION_CANCEL:
                    tv.setText(notClickedString, TextView.BufferType.SPANNABLE);
                    break;
                }
                return true;
            }
        });
    

    Another solution is to use Html.fromHtml(...) , where the text inside has links tags ("") .

    If you wish for another solution, check this post.

提交回复
热议问题