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