TextView 富文本学习六 - 设置了ClickableSpan导致内存泄漏

1 设置ClickableSpan导致内存泄漏

 spannable.setSpan(new ClickableSpan() {
                       @Override
                       public void onClick(View widget) {
                          
                       }

                       public void updateDrawState(TextPaint ds) {
                           ds.setColor(mContext.getResources().getColor();
                           ds.setUnderlineText(false);
                       }
                   }, start, start + tagNameMatch.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

导致内存泄漏的原因:
https://stackoverflow.com/questions/28539216/android-textview-leaks-with-setmovementmethod

Using ClickableSpan may still cause leaks even on versions higher than KitKat. If you look into implementation of the ClickableSpan you will notice that it doesn't extend NoCopySpan, so it leaks in onSaveInstanceState() like described in @DmitryKorobeinikov and @ChrisHorner answers. So the solution would be to create a custom class that extends ClickableSpan and NoCopySpan.

解决办法也来自上面的网址:

public static class NoRefCopySpan  extends ClickableSpan implements NoCopySpan{

        @Override
        public void onClick(@NonNull View widget) {

        }

        @Override
        public void updateDrawState(TextPaint ds) {
           super.updateDrawState(ds);
        }

    }

使用

         spannable.setSpan(new NoRefCopySpan() {
                  @Override
                  public void onClick(View widget) { 
                  }
    
                 public void updateDrawState(TextPaint ds) {
                             
                }
                }, start, start + tagNameMatch.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,141评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 14,242评论 3 20
  • 头顶浮动着充盈的空气 我却不能呼吸 鱼儿披着鳞片 在眼前游弋 伸手触摸 却像地狱到天堂的距离 错杂的水草缠绕我的脚...
    肖玉楼阅读 3,720评论 0 8
  • 风不知跑哪去了 窗外的竹寂寞的了 院里的小池塘也乖了 夜,如白纸般的寂静 淘气的春雨非要调皮调皮 拨弄拨弄这沉寂 ...
    小胡巴阅读 3,437评论 17 35
  • 竹枝词九首(其二) 唐 刘禹锡 杨柳青青江水平, 闻郎岸上踏歌声。 东边日出西边雨 道是无晴却有晴。
    水火同源阅读 3,081评论 0 13