Android TypeArray

阅读数:66 评论数:0

跳转到新版页面

分类

python/Java

正文

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




相关推荐

程序启动图标(Logo)\底部菜单图标 小屏ldpi() 36x36 px 中屏mdpi(160dpi) 48x48 px 大屏hdpi(240dp

一、预备知识 Fragment必须嵌入到Activity中, 当Activity暂停时, 其中的所有片段也会暂停, 当Activity被销毁时,所有片段也会被销毁. 不过,  当Activity正在运

该属性是当一个view获取焦点时, 定义ViewGroup和其子控件两者之间的关系, 属性的值有三种: (1) beforeDescendants: viewgroup会优先其子控

只有在LinearLayout时, 该属性才有效. android:layout_w

gravity的中文意思就是"重心", 就是表示view横向和纵向的依靠位置. a

android webview从Lollipop(5.0)开始webview默认不允许混合模式, https当中不能加载http资源, 而开发的时候可能使用的是https的链接, 但是链接中的图

从网上查找资料,发现有多种方式, 我用了其中最简单的方式: 使用java.lang.String的replace方法, <pre class="language-marku

当我们的项目的某些属性和第三方库中属性有冲突或者我们想修改第三方库中某些资源时,我们就需要使用tools:replace来处理。 1、有冲突的情况 比如第三方库中

在Android中,使用Span定义文本的样式,通过Span改变几个文字的颜色,Span能够改变TextPaint属性,在Canvas上绘制,甚至是改变文本的布局和影响行高这样的元素。Span是

作用 xmlns:tools="http://schemas.android.com/tools"