这是为了缓存目的而需要的。当您调用recycle
时,表示该对象可以从此点开始重复使用。在内部,TypedArray
包含几个数组,因此为了不在每次使用TypedArray
时分配内存,它被缓存在Resources
类中作为静态字段。您可以查看TypedArray.recycle()
方法代码:
/**
* Give back a previously retrieved StyledAttributes, for later re-use.
*/
public void recycle() {
synchronized (mResources.mTmpValue) {
TypedArray cached = mResources.mCachedStyledAttributes;
if (cached == null || cached.mData.length < mData.length) {
mXml = null;
mResources.mCachedStyledAttributes = this;
}
}
}
因此,当您调用recycle
时,您的TypedArray
对象只是返回到缓存中。
@Andrei Mankevich 我刚刚查看了最新版本的Android SDK,似乎对recycle()进行了一些更改。请检查下面的代码:
/**
* Recycle the TypedArray, to be re-used by a later caller. After calling
* this function you must not ever touch the typed array again.
*/
public void recycle() {
if (mRecycled) {
throw new RuntimeException(toString() + " recycled twice!");
}
mRecycled = true;
// These may have been set by the client.
mXml = null;
mTheme = null;
mResources.mTypedArrayPool.release(this);
}