为什么需要在TypedArray后调用recycle

10 篇文章 0 订阅

当我们在自定义控件的属性时,例如:

<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类中的静态字段中,这样就不用每次使用前都需要分配内存。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值