【问题标题】:EditText addTextChangedListener cause memory leakEditText addTextChangedListener 导致内存泄漏
【发布时间】:2015-05-22 04:00:36
【问题描述】:

我使用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中找到的以下代码sn-p

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

【问题讨论】:

    标签: android memory-leaks leakcanary


    【解决方案1】:

    我找到了一个相关话题Android memory leak on textview

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

    【讨论】: