obtainStyledAttributes是干什么的
有过自定义属性或者查看过系统View相关子类源码的人可能对这个方法都不会陌生。
该方法是Context类为我们提供的获取style中特定属性值的方法。通过这个方法,我们就可以获取在style中定义的各种属性值,然后根据获取到的不同的属性值实现差异化的效果。
一种典型的使用方式是:
//TextView 构造方法片选代码
//首先通过obtainStyledAttributes获取TypedArray
TypedArray a = theme.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.TextViewAppearance, defStyleAttr, defStyleRes);
//接着从TypedArray中提取相应的值,此处提取的是resourceId,对于的attr声明应为“reference”
//除此之外,TypedArray还有getInt,getDrawable等一系列方法用于提取其他类型的值。
int ap = a.getResourceId(
com.android.internal.R.styleable.TextViewAppearance_textAppearance, -1);
//回收TypedArray
a.recycle();
从以上代码片看到调用obtainStyledAttributes的变量是theme,其实是因为context中的该方法最终也是调用其持有的theme对象的该方法,因此是一致的。如下:
//Context obtainStyledAttributes实现
public final TypedArray obtainStyledAttributes(
AttributeSet set, @StyleableRes int[] attrs, @AttrRes int defStyleAttr,
@StyleRes int defStyleRes) {
return getTheme().obtainStyledAttributes(
set, attrs, defStyleAttr, defStyleRes);
}
既然如此,我们就直接分析Theme中的obtainStyledAttributes方法。
obtainStyledAttributes API解析
以上是文档中对该方法的说明。我们先从参数部分看。该方法总共有四个参数:
参数名 | 说明 |
---|---|
set | 直接内嵌在View中的属性集合&# |