為什么需要在TypedArray后調用recycle


當我們沒有在使用TypedArray后調用recycle,編譯器會提示“This TypedArray should be recycled after use with #recycle()”。

官方的解釋是:回收TypedArray,以便后面重用。在調用這個函數后,你就不能再使用這個TypedArray。

在TypedArray后調用recycle主要是為了緩存。當recycle被調用后,這就說明這個對象從現在可以被重用了。TypedArray 內部持有部分數組,它們緩存在Resources類中的靜態字段中,這樣就不用每次使用前都需要分配內存。你可以看看TypedArray.recycle()中的代碼:

 1 /**
 2  * Give back a previously retrieved StyledAttributes, for later re-use.
 3  */
 4 public void recycle() {
 5     synchronized (mResources.mTmpValue) {
 6         TypedArray cached = mResources.mCachedStyledAttributes;
 7         if (cached == null || cached.mData.length < mData.length) {
 8             mXml = null;
 9             mResources.mCachedStyledAttributes = this;
10         }
11     }
12 }

 

 

參考鏈接

http://stackoverflow.com/questions/13805502/why-do-you-have-to-recycle-a-typedarray

http://developer.android.com/reference/android/content/res/TypedArray.html#recycle%28%29


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM