关于TypedArray 的使用

我们在使用自定义控件的时候,很多情况会用到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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值