Android中TypedArray用完为什么要recycle()

首先先看下TypedArray实例化源码:

static TypedArray obtain(Resources res, int len) {
    TypedArray attrs = res.mTypedArrayPool.acquire();
    if (attrs == null) {
        attrs = new TypedArray(res);
    }

    attrs.mRecycled = false;
    // Reset the assets, which may have changed due to configuration changes
    // or further resource loading.
    attrs.mAssets = res.getAssets();
    attrs.mMetrics = res.getDisplayMetrics();
    attrs.resize(len);
    return attrs;
}

可以看出,TypedArray的实例是从一个Array Pool中 获取的,池的描述如下:

// Pool of TypedArrays targeted to this Resources object.
final SynchronizedPool<TypedArray> mTypedArrayPool = new SynchronizedPool<>(5);
池中默认大小为5。 程序在运行时维护了一个 TypedArray的池,程序调用时,会向该池中请求一个实例,用完之后,调用 recycle() 方法来释放该实例,从而使其可被其他模块复用。

那为什么要使用这种模式呢?答案也很简单,TypedArray的使用场景之一,就是上述的自定义View,会随着 Activity的每一次Create而Create,因此,需要系统频繁的创建array,对内存和性能是一个不小的开销,如果不使用池模式,每次都让GC来回收,很可能就会造成OutOfMemory。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android ,我们可以使用自定义属性来设置边距。下面是一个示例代码,展示了如何在 XML 布局文件使用自定义属性来设置边距: 首先,在 res/values/attrs.xml 文件定义自定义属性: ```xml <resources> <declare-styleable name="CustomView"> <attr name="customMargin" format="dimension" /> </declare-styleable> </resources> ``` 然后,在布局文件使用自定义属性来设置边距: ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello World!" android:layout_margin="@style/CustomView.customMargin" /> </LinearLayout> ``` 在上述示例,我们在 TextView 的 layout_margin 属性使用了 @style/CustomView.customMargin,这样就可以设置自定义的边距。 当然,你也可以在 Java 代码使用自定义属性来设置边距。首先,获取自定义属性的值: ```java TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomView); int customMargin = typedArray.getDimensionPixelSize(R.styleable.CustomView_customMargin, 0); typedArray.recycle(); ``` 然后,将获取到的边距值应用到视图: ```java LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.setMargins(customMargin, customMargin, customMargin, customMargin); textView.setLayoutParams(params); ``` 这样就可以通过自定义属性来设置边距了。希望能帮到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值