handle textview link click in my android app

前端 未结 12 912
迷失自我
迷失自我 2020-11-22 04:33

I\'m currently rendering HTML input in a TextView like so:

tv.setText(Html.fromHtml(\"test\"));

The HTML b

12条回答
  •  名媛妹妹
    2020-11-22 05:12

    Another way, borrows a bit from Linkify but allows you to customize your handling.

    Custom Span Class:

    public class ClickSpan extends ClickableSpan {
    
        private OnClickListener mListener;
    
        public ClickSpan(OnClickListener listener) {
            mListener = listener;
        }
    
        @Override
        public void onClick(View widget) {
           if (mListener != null) mListener.onClick();
        }
    
        public interface OnClickListener {
            void onClick();
        }
    }
    

    Helper function:

    public static void clickify(TextView view, final String clickableText, 
        final ClickSpan.OnClickListener listener) {
    
        CharSequence text = view.getText();
        String string = text.toString();
        ClickSpan span = new ClickSpan(listener);
    
        int start = string.indexOf(clickableText);
        int end = start + clickableText.length();
        if (start == -1) return;
    
        if (text instanceof Spannable) {
            ((Spannable)text).setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            SpannableString s = SpannableString.valueOf(text);
            s.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            view.setText(s);
        }
    
        MovementMethod m = view.getMovementMethod();
        if ((m == null) || !(m instanceof LinkMovementMethod)) {
            view.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }
    

    Usage:

     clickify(textView, clickText,new ClickSpan.OnClickListener()
         {
            @Override
            public void onClick() {
                // do something
            }
        });
    

提交回复
热议问题