EditText addTextChangedListener 导致内存泄漏

EditText addTextChangedListener cause memory leak

我使用 LeakCanary 检查我的应用程序是否存在内存泄漏, 它报告泄漏如下

 public AutofitHelper setEnabled(boolean enabled) {
    if (mEnabled != enabled) {
        mEnabled = enabled;

        if (enabled) {
            mTextView.addTextChangedListener(mTextWatcher);
            mTextView.addOnLayoutChangeListener(mOnLayoutChangeListener);

            autofit();
        } else {
        android.util.Log.i("linlian","AutofitHelper.setEnabled()remove="+mTextView);
            mTextView.removeTextChangedListener(mTextWatcher);
            mTextView.removeOnLayoutChangeListener(mOnLayoutChangeListener);

            mTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
        }
    }
    return this;
}

代码调用setEnable(true)为TextView添加addTextChangedListener 我已经将 setEnable(false) 添加到 removeTextChangedListener,但是 这还不够,还有一个静态的TextLine.sCached引用,如何 释放 sCashed.

我在 TextLine 中找到的以下代码片段

static TextLine recycle(TextLine tl) {
    tl.mText = null;
    tl.mPaint = null;
    tl.mDirections = null;

    tl.mMetricAffectingSpanSpanSet.recycle();
    tl.mCharacterStyleSpanSet.recycle();
    tl.mReplacementSpanSpanSet.recycle();

    synchronized(sCached) {
        for (int i = 0; i < sCached.length; ++i) {
            if (sCached[i] == null) {
                sCached[i] = tl;
                break;
            }
        }
    }
    return null;
}

但是,如何以正确的方式使用它来回收静态 sCashed

我找到了一个相关主题

Utils.clearTextLineCache() 可能是一个很好的解决方法。