关于TypedArray 的使用

本文介绍了 TypedArray 的概念及其在 Android 开发中的应用。它是一种通过上下文获取的数组容器,用于存储样式属性值。文中提供了从 PtrFrameLayout 中截取的具体使用示例,并强调了使用完毕后需要调用 recycle 方法来释放资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们在使用自定义控件的时候,很多情况会用到TypedArray 。

开发者平台解释:


上边的意思:

TypedArray是一个通过上下文的对象 context.obtainStyledAttributes(AttributeSet,int[],int,int)方法或者context.obtainAttributes(AttributeSet,int[]) 获取到的数组数值的容器。确保使用完 TypedArray 对象之后,调用TypedArray对象的recycle()方法回收资源。通常通过它的 obtainStyledAttributes方法获取到相应位置的数值。;


总结一下,就是它是存储一些数值的数组容器,使用好之后要调用typedArray.recycle()方法回收资源。


具体使用方法如下,截取自 PtrFrameLayout:

public PtrFrameLayout(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    mPtrIndicator = new PtrIndicator();

    TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.PtrFrameLayout, 0, 0);
    if (arr != null) {

        mHeaderId = arr.getResourceId(R.styleable.PtrFrameLayout_ptr_header, mHeaderId);
        mContainerId = arr.getResourceId(R.styleable.PtrFrameLayout_ptr_content, mContainerId);

        mPtrIndicator.setResistance(
                arr.getFloat(R.styleable.PtrFrameLayout_ptr_resistance, mPtrIndicator.getResistance()));

        mDurationToClose = arr.getInt(R.styleable.PtrFrameLayout_ptr_duration_to_close, mDurationToClose);
        mDurationToCloseHeader = arr.getInt(R.styleable.PtrFrameLayout_ptr_duration_to_close_header, mDurationToCloseHeader);

        float ratio = mPtrIndicator.getRatioOfHeaderToHeightRefresh();
        ratio = arr.getFloat(R.styleable.PtrFrameLayout_ptr_ratio_of_header_height_to_refresh, ratio);
        mPtrIndicator.setRatioOfHeaderHeightToRefresh(ratio);

        mKeepHeaderWhenRefresh = arr.getBoolean(R.styleable.PtrFrameLayout_ptr_keep_header_when_refresh, mKeepHeaderWhenRefresh);

        mPullToRefresh = arr.getBoolean(R.styleable.PtrFrameLayout_ptr_pull_to_fresh, mPullToRefresh);
        arr.recycle();
    }

    mScrollChecker = new ScrollChecker();

    final ViewConfiguration conf = ViewConfiguration.get(getContext());
    mPagingTouchSlop = conf.getScaledTouchSlop() * 2;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值