Search code examples
androidmemory-leaksleakcanary

EditText addTextChangedListener cause memory leak


I use LeakCanary to check my app for memory leak, and it reports a leak as follow enter image description here

 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;
}

the code calls setEnable(true) to add addTextChangedListener for TextView and i have already added setEnable(false) to removeTextChangedListener, but this is not enough, there is a static TextLine.sCached reference, how to release the sCashed.

The follow code snippet I found in 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;
}

but, how to use it in correct way to recycle the static sCashed?


Solution

  • I found a related topic Android memory leak on textview

    the Utils.clearTextLineCache() maybe a good workarounds.