setSpan 冲突问题

2017-06-01  本文已影响0人  小面包屑

参考
http://stackoverflow.com/questions/29505622/spannablestringbuilder-set-clickablespan-more-than-once-cant-click
http://stackoverflow.com/questions/13118278/why-cant-use-the-same-span-object-to-setspan-above-twice
http://stackoverflow.com/questions/20077457/spannablestring-changes-color-first-time-but-not-when-reused
http://www.jianshu.com/p/be0d79b9d5e6

项目中要求做几个链接,点击跳转到不同的h5页面. 根据效果图,决定使用富文本做。
先贴修改后的代码:

自定义一个ClickableSpan

public class CustomUrlSpan extends ClickableSpan {

    private String url;
    private String title;


    public CustomUrlSpan( String url, String title) {
        this.url = url;
        this.title = title;
    }

    @Override
    public void onClick(View widget) {

        Intent intent = new Intent(ContextUtils.getContext(), WebViewActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Constant.WEB_URL, url);
        intent.putExtra(Constant.WEB_TITLE,title);
        ContextUtils.getContext().startActivity(intent);

    }
}

根据不同的航班,拼接不同的协议文本放到textview

StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("已阅读并同意<a href='" + HttpServiceConstants.FLIGHT_AIRPORT_AGREEN_CONSIGN_URL + "' > " + getActivity().getString(R.string.frm_flight_order_protocol) + " </a>");
String dot = "<font color='" + ContextCompat.getColor(ContextUtils.getContext(), R.color.txt_blue) + "'> 、 </font>";
stringBuffer.append(dot).append("<a href='" + Constant.WEB_URL_BATTERY + "' > " + getActivity().getString(R.string.frm_flight_order_protocol_battery) + " </a>");
   flightCabinselTravelBinding.tvFlightProtocol.setText(HtmlUtil.fromHtml(stringBuffer.toString()));
        flightCabinselTravelBinding.tvFlightProtocol.setMovementMethod(new FixedLinkMovementMethod());


        CharSequence text = flightCabinselTravelBinding.tvFlightProtocol.getText();
        int end = text.length();
        Spannable spannable = (Spannable) text;
        URLSpan[] urlSpans = spannable.getSpans(0, end, URLSpan.class);
        if (urlSpans.length == 0) {
            return;
        }

       SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text);


        // 循环遍历并拦截 所有http://开头的链接
        for (URLSpan uri : urlSpans) {
            final String url = uri.getURL();
            if (url.indexOf("http") == 0) {
                CustomUrlSpan customUrlSpan = null;

                //托运协议
                if (url.equals(HttpServiceConstants.FLIGHT_AIRPORT_AGREEN_CONSIGN_URL)) {
                    customUrlSpan = new CustomUrlSpan(url, getActivity().getString(R.string.frm_flight_order_protocol));
                }

                //西部
                else if (url.equals(Constant.WEB_URL_WEST)) {

                    customUrlSpan = new CustomUrlSpan(url, getActivity().getString(R.string.frm_flight_order_protocol_west));

                }

                //深圳航空
                else if (url.equals(Constant.WEB_URL_SZ)) {

                    customUrlSpan = new CustomUrlSpan(url, getActivity().getString(R.string.frm_flight_order_protocol_sz));


                }

                //锂电池及危险品须知
                else if (url.equals(Constant.WEB_URL_BATTERY)) {

                    customUrlSpan = new CustomUrlSpan(url, getActivity().getString(R.string.frm_flight_order_protocol_battery));

                }

                if (customUrlSpan != null) {

                    // The original URLSpan needs to be removed to block the behavior of browser opening
                    spannableStringBuilder.removeSpan(uri);

                    spannableStringBuilder.setSpan(CharacterStyle.wrap(customUrlSpan), spannable.getSpanStart(uri),
                            spannable.getSpanEnd(uri), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);


                }


            }
        }

        flightCabinselTravelBinding.tvFlightProtocol.setText(spannableStringBuilder);

开发过程中遇到的问题:

1、点击文字链接跳转到了系统自带浏览器当中,CustomUrlSpan的点击事件并没有执行

2、在webviewActivity中打开链接,返回退出该富文本页面。再次进入,更改后的协议文本拼接没错,但textView展示出来的文本还是之前的文本,并没有根据拼接内容而改变。


问题1 解决:

setSpan 的时候,需要先去掉原本的UrlSpan ,阻止链接在系统的浏览器打开。

 // The original URLSpan needs to be removed to block the behavior of browser opening
 spannableStringBuilder.removeSpan(uri);

问题2 解决:

先要了解 <b>LinkMovementMethod</b> 、 <b>SpannableStringBuilder</b>、<b>CharacterStyle.wrap()</b>

LinkMovementMethod

A movement method that traverses links in the text buffer and scrolls if necessary. Supports clicking on links with DPad Center or Enter.

简单来说,就是让链接与滚动生效。

富文本的点击事件会分发到这个对象里面,那么我们可以在onTouchEvent()中来处理这个点击事件。
代码中过滤出了ClickableSpan,执行click事件


public class FixedLinkMovementMethod extends LinkMovementMethod {

    @Override
    public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
        int action = event.getAction();

        if (action == MotionEvent.ACTION_UP ||
                action == MotionEvent.ACTION_DOWN) {
            int x = (int) event.getX();
            int y = (int) event.getY();

            x -= widget.getTotalPaddingLeft();
            y -= widget.getTotalPaddingTop();

            x += widget.getScrollX();
            y += widget.getScrollY();

            Layout layout = widget.getLayout();
            int line = layout.getLineForVertical(y);
            int off = layout.getOffsetForHorizontal(line, x);

            CharacterStyle[] candidates = buffer.getSpans(off, off, CharacterStyle.class);

            ClickableSpan clickableSpan = null;

            for (CharacterStyle characterStyle : candidates) {
                if (characterStyle.getUnderlying() instanceof ClickableSpan) {
                    clickableSpan = (ClickableSpan) characterStyle.getUnderlying();
                    break;
                }
            }

            if (clickableSpan != null) {
                if (action == MotionEvent.ACTION_UP) {
                    clickableSpan.onClick(widget);
                } else if (action == MotionEvent.ACTION_DOWN) {
                    Selection.setSelection(buffer,
                            buffer.getSpanStart(clickableSpan),
                            buffer.getSpanEnd(clickableSpan));
                }

                return true;
            } else {
                Selection.removeSelection(buffer);
            }
        }

        return super.onTouchEvent(widget, buffer, event);
    }

}

SpannableStringBuilder

You can't reuse the same span multiple times. Even if the span is exactly the same, you need to create a unique span for each section of the string you are wanting to change.

不要多次重复使用相同的span , 最好创建一个唯一的span,避免出现之前的span被改变。

When you pass same span by setSpan method, it will check if spans array have same one and replace old start and end value by news.

当使用setSpan方法的时候,方法中会判断是否存在一个相同的spans array ,start 到 end 的值会被最新的替换。

也就是说,复用span的话,之前的span可能会被最新的span改变。

/* package */ void setSpan(Object what, int start, int end, int flags) {
    ...
  for (int i = 0; i < count; i++) {
    if (spans[i] == what) {
        int ostart = mSpanStarts[i];
        int oend = mSpanEnds[i];

        if (ostart > mGapStart)
            ostart -= mGapLength;
        if (oend > mGapStart)
            oend -= mGapLength;

        mSpanStarts[i] = start;
        mSpanEnds[i] = end;
        mSpanFlags[i] = flags;

        if (send) sendSpanChanged(what, ostart, oend, nstart, nend);

        return;
    }
}

    ...
}

CharacterStyle.wrap()

CharacterStyle是个抽象类,字符级别的Span都需要继承这个类
CharacterStyle拥有很多子类(BackgroundColorSpan,ClickableSpan,ImageSpan,TypefaceSpan等)
一个CharacterStyle类型的Span只能给一个Spaned片段使用,如果想这个Span给多个片段使用可以使用wrap方法。
其实就是复制了一个CharacterStyle。

public static CharacterStyle wrap(CharacterStyle cs) {
    if (cs instanceof MetricAffectingSpan) {
        return new MetricAffectingSpan.Passthrough((MetricAffectingSpan) cs);
    } else {
        return new Passthrough(cs);
    }
}

if you use CharacterStyle.wrap() your span is no longer a ClickableSpan instance, but a CharacterStyle.Passthrough instance instead. Therefore getSpans() does not return it anymore and it's no longer clickable.

如果使用了CharacterStyle.wrap() , 那么span不会是一个ClickableSpan ,也就是说点击事件会失效。

A given CharacterStyle can only applied to a single region of a given Spanned. If you need to attach the same CharacterStyle to multiple regions, you can use this method to wrap it with a new object that will have the same effect but be a distinct object so that it can also be attached without conflict.

有多个片段的时候使用,解决attached的冲突问题。


原来如此,是因为没有使用CharacterStyle.wrap()而导致的问题。最后再自定义一个LinkMovementMethod处理click事件,问题就解决了。

上一篇 下一篇

猜你喜欢

热点阅读