Android(安卓)TypeArray
16lz
2021-01-24
在Anrdoid自定义View时候,需要使用TypedArray来获取XML layout中的属性值,使用完之后,需要调用recycle()方法将TypeArray回收。
那么TypeArray是什么呢?
首先,它的常规用法
TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PieChart,0,0);try { mShowText = array.getBoolean(R.styleable.PieChart_showText,false); mTextPos = array.getInteger(R.styleable.PieChart_labelPosition,0);}finally { array.recycle();}
可见,TypeArray不是我们new出来的,而是调用了obtainStyledAttributes方法得到的对象,认方法实现如下:
public TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes) { final int len = attrs.length; final TypedArray array = TypedArray.obtain(Resources.this, len); // other code ..... return array;}
进一步查看该静态方法
/** * Container for an array of values that were retrieved with * {@link Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int)} * or {@link Resources#obtainAttributes}. Be * sure to call {@link #recycle} when done with them. * * The indices used to retrieve values from this structure correspond to * the positions of the attributes given to obtainStyledAttributes. */public class TypedArray { static TypedArray obtain(Resources res, int len) { final TypedArray attrs = res.mTypedArrayPool.acquire(); if (attrs != null) { attrs.mLength = len; attrs.mRecycled = false; final int fullLen = len * AssetManager.STYLE_NUM_ENTRIES; if (attrs.mData.length >= fullLen) { return attrs; } attrs.mData = new int[fullLen]; attrs.mIndices = new int[1 + len]; return attrs; } return new TypedArray(res, new int[len*AssetManager.STYLE_NUM_ENTRIES], new int[1+len], len); } // Other members ......}
显然是一个典型的单例模式,这个array是从一个array poolr 池中获取的。
TypedArray的使用场景之一,就是上述的自定View,会随着Activity的每一次Create而Create,因此,需要系统频繁的创建array,对内存和性能是一个不小的开销,如果不使用池模式,每次都让GC来回收,很可能会造成OutOfMemory。
更多相关文章
- Android判断某一应用是否正在运行与判断某一Service是否正在运行
- android 记录和恢复ListView滚动的位置 四种方法
- android中EditText只允许输入汉字(过滤汉字)
- Android(安卓)5.0以上版本去掉Button自带阴影效果的方法
- android CTS测试使用方法
- Android(安卓)MediaPlayer类
- Android(安卓)WebView开发常见问题
- Android(安卓)启动分析-init进程&init.rc
- Android(安卓)后台任务(六)IntentService