当我们在自定义控件的属性时,例如:
<span style="white-space:pre"> </span>public ViewPagerIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator);
mTabVisibleCount = a.getInteger(R.styleable.ViewPagerIndicator_item_count, COUNT_DEFAULT_TAB);
if(mTabVisibleCount< 0 )
mTabVisibleCount=COUNT_DEFAULT_TAB;
a.recycle();
}
往往需要获得属性集,而最后都需要调用TypedArray.recycle()方法,这是为什么呢?
在stackoverflow获得的解释是:
This is required for caching purporse. When you call recycle
it means that this object can be reused from this point. Internally TypedArray
contains few arrays so in order not to allocate memory each time when TypedArray
is used it is cached in Resources
class as static field. You can look at TypedArray.recycle()
method code:
/**
* 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);
}
回收TypedArray,以便后面重用。在调用这个函数后,你就不能再使用这个TypedArray。在TypedArray后调用recycle主要是为了缓存。当recycle被调用后,这就说明这个对象从现在可以被重用了。TypedArray 内部持有部分数组,它们缓存在Resources类中的静态字段中,这样就不用每次使用前都需要分配内存。