为什么需要在TypedArray后调用recycle

这个是我在认识declare-styleable,了解自定义view的在textview源码中看到的很不解,今天无意间在网上看到了,记下来说下。
当我们没有在使用TypedArray后调用recycle,编译器会提示“This TypedArray should be recycled after use with #recycle()”。

官方的解释是:回收TypedArray,以便后面重用。在调用这个函数后,你就不能再使用这个TypedArray。

在TypedArray后调用recycle主要是为了缓存。当recycle被调用后,这就说明这个对象从现在可以被重用了。TypedArray 内部持有部分数组,它们缓存在Resources类中的静态字段中,这样就不用每次使用前都需要分配内存。你可以看看TypedArray.recycle()中的代码:

 /**
   * Give back a previously retrieved StyledAttributes, for later re-use.
  */
  public void recycle() {
      synchronized (mResources.mTmpValue) {
          TypedArray cached = mResources.mCachedStyledAttributes;
          if (cached == null || cached.mData.length < mData.length) {
              mXml = null;
             mResources.mCachedStyledAttributes = this;
         }
     }
 }

从mResources.mCachedStyledAttributes = this;这就把TypedArray缓冲到Resources类中的静态字段中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Android 中,你可以通过以下步骤在代码中动态调用自定义属性: 1. 首先,在 res/values/attrs.xml 文件中定义自定义属性。例如,我们定义一个名为 customMargin 的自定义属性: ```xml <resources> <declare-styleable name="CustomView"> <attr name="customMargin" format="dimension" /> </declare-styleable> </resources> ``` 2. 在你的自定义视图类中获取和使用自定义属性的值。例如,我们在 CustomView 类中获取 customMargin 的值并应用到视图上: ```java public class CustomView extends View { private int customMargin; public CustomView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } private void init(AttributeSet attrs) { TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.CustomView); customMargin = typedArray.getDimensionPixelSize(R.styleable.CustomView_customMargin, 0); typedArray.recycle(); // 在这里可以根据 customMargin 的值做相应的操作,例如设置边距等 // ... } } ``` 在上述示例中,我们通过 getContext().obtainStyledAttributes(attrs, R.styleable.CustomView) 方法获取 TypedArray 对象,然后使用 getDimensionPixelSize 方法获取 customMargin 属性的值。 3. 在 XML 布局文件中使用自定义视图,并设置自定义属性的值。例如: ```xml <com.example.CustomView android:layout_width="match_parent" android:layout_height="wrap_content" app:customMargin="16dp" /> ``` 在上述示例中,我们使用 app:customMargin="16dp" 来设置 customMargin 的值为 16dp。 通过以上步骤,你可以在代码中动态调用自定义属性,并根据其值做相应的操作。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值