带有 Spannable 的自定义 Textview 中的内存泄漏 Android

Memory Leak in Custom Textview with Spannable Android

我有一个自定义文本视图,它有五个城市名称和每个城市名称的可跨越式点击侦听器。代码如下

/**
 * Created by @raj on 26/04/18.
 */
class TopCitiesTextView : TextView {

    private  var mListener: OnCityClickListener? = null

    constructor(ctx: Context?) : super(ctx) {
        initView(ctx, null, 0)
    }

    constructor(ctx: Context?, attrs: AttributeSet?) : super(ctx, attrs) {
        initView(ctx, attrs, 0)
    }

    constructor(ctx: Context?, attrs: AttributeSet?, defStyle: Int) : super(ctx, attrs, defStyle) {
        initView(ctx, attrs, defStyle)
    }

    private fun initView(ctx: Context?, attrs: AttributeSet?, defStyle: Int) {
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        val cityArray: Array<out String> = context.resources.getStringArray(R.array.top_cities_view_text)
        val spannableString: SpannableString = SpannableString(cityArray[0])
        this.text = spannableString
        this.append(" ")
        for (i in 1 until cityArray.size) {
            val citySpannableString = SpannableString(cityArray[i])
            citySpannableString.setSpan(object : ClickableSpan() {
                override fun onClick(widget: View?) {
                        mListener?.onCityClicked(cityArray[i])
                }
                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.isUnderlineText = false
                }

            }, 0, citySpannableString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            this.append(citySpannableString)
            if (i != cityArray.size-1)
                this.append(", ")
        }
        movementMethod = LinkMovementMethod.getInstance()
    }

    fun setCityClickListener(listener: OnCityClickListener) {
        this.mListener = listener
    }

    interface OnCityClickListener {
        fun onCityClicked(city: String?)
    }
}

但问题是我在片段的布局 (xml) 文件中使用此文本视图时发生内存泄漏。

这里是leakcanary的截图。

如何消除此内存泄漏?

从 Activity 的 onDestroy 中的文本中删除 ClickableSpan 以避免泄漏。

    if (textView.getText() instanceof SpannableString) {
          SpannableString spannableStr = (SpannableString) textView.getText();
          ClickableSpan[] spans = spannableStr.getSpans(0, spannableStr.length(), ClickableSpan.class);
          for (ClickableSpan span : spans) {
             spannableStr.removeSpan(span);
          }
          textView.setText(spannableStr);
    }