在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。

 

更多相关文章

  1. Android判断某一应用是否正在运行与判断某一Service是否正在运行
  2. android 记录和恢复ListView滚动的位置 四种方法
  3. android中EditText只允许输入汉字(过滤汉字)
  4. Android(安卓)5.0以上版本去掉Button自带阴影效果的方法
  5. android CTS测试使用方法
  6. Android(安卓)MediaPlayer类
  7. Android(安卓)WebView开发常见问题
  8. Android(安卓)启动分析-init进程&init.rc
  9. Android(安卓)后台任务(六)IntentService

随机推荐

  1. android开发音乐播放器之进度条
  2. NDK 在 Android(安卓)studio如何使用(Andr
  3. Android(安卓)Developers:拖动和缩放
  4. Android(安卓)Studio 3.3.2 正式版的安装
  5. Android(安卓)OkHttp4 RequestBody.creat
  6. 开发小技巧--google推荐的底部导航栏的使
  7. Android(安卓)实现多图分享到微信朋友圈
  8. Android中MPAndroidChart使用Demo
  9. Android客户端+mysql+springmvc服务器端
  10. Android(安卓)NDK:①开发环境的搭建(Wind