Control onclicklistener in autolink enabled textview

前端 未结 9 2644
一向
一向 2020-12-08 19:13

I am using a TextView for which I have set autolink=\"web\" property in XML file. I have also implemented the onClickListener for this TextView. Th

9条回答
  •  情深已故
    2020-12-08 19:33

    private void fixTextView(TextView tv) {
        SpannableString current = (SpannableString) tv.getText();
        URLSpan[] spans =
                current.getSpans(0, current.length(), URLSpan.class);
    
        for (URLSpan span : spans) {
            int start = current.getSpanStart(span);
            int end = current.getSpanEnd(span);
    
            current.removeSpan(span);
            current.setSpan(new DefensiveURLSpan(span.getURL()), start, end,
                    0);
        }
    }
    
    public static class DefensiveURLSpan extends URLSpan {
    
        public final static Parcelable.Creator CREATOR =
                new Parcelable.Creator() {
    
            @Override
            public DefensiveURLSpan createFromParcel(Parcel source) {
                return new DefensiveURLSpan(source.readString());
            }
    
            @Override
            public DefensiveURLSpan[] newArray(int size) {
                return new DefensiveURLSpan[size];
            }
    
        };
    
    private String mUrl;
    
    public DefensiveURLSpan(String url) {
        super(url);
        mUrl = url;
    }
    
        @Override
        public void onClick(View widget) {
            // openInWebView(widget.getContext(), mUrl); // intercept click event and do something.
            // super.onClick(widget); // or it will do as it is.
        }
    }
    

    You would then call fixTextView(textViewContent); on the view after it is declared (via inflation or findViewById) or added to the window (via addView)

    This includes the missing requirement to set a CREATOR when extending a Parcelable.

    It was proposed as an edit, but rejected. Unfortunately, now future users will have to find out the original one is incomplete first. Nice one, reviewers!

提交回复
热议问题