如何在代码中获取attr属性的值
获取arrt的值
有时候我们需要把颜色,数值写成attr属性,这样做是为了屏蔽开发者对应具体数值,比如我们需要设置不同主题下的主色,副色,或者是不同版本的ActionBar大小,亦或者是不同Dpi下的DrawerLayout的宽度等。
在xml里,我们可以简单的引用attr属性值,例如:
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
当然,我们有时候也需要在代码中获取attr属性值:
TypedValue typedValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.yourAttr, typedValue, true);
// For string
typedValue.string
typedValue.coerceToString()
// For other data
typedValue.resourceId
typedValue.data;
获取arrt样式中的值
以上是针对个体数值根据不同类型来获取的,如果想要获取 style 的话,需要在拿到 resourceId 之后再进一步获取具体数值,以 TextAppearance.Large 为例:
<style name="TextAppearance.Large">
<item name="android:textSize">22sp</item>
<item name="android:textStyle">normal</item>
<item name="android:textColor">?textColorPrimary</item>
</style>
TypedValue typedValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.textAppearanceLarge, typedValue, true);
int[] attribute = new int[] { android.R.attr.textSize };
TypedArray array = context.obtainStyledAttributes(typedValue.resourceId, attribute);
int textSize = array.getDimensionPixelSize(0 /* index */, -1 /* default size */);
array.recycle();
注意,要记得调用 TypedArray.recycle() 方法回收资源。
Android 源码中的使用实例
Drawable drawable = context.getPackageManager()
.getResourcesForApplication(tile.iconPkg).getDrawable(tile.iconRes, null);
if (!tile.iconPkg.equals(context.getPackageName()) && drawable != null) {
// If this drawable is coming from outside Settings, tint it to match the color.
TypedValue tintColor = new TypedValue();
context.getTheme().resolveAttribute(com.android.internal.R.attr.colorAccent,
tintColor, true);
drawable.setTint(tintColor.data);
}
tileIcon.setImageDrawable(drawable);
上面的代码是在Android M设置中的拷贝出来的代码,这个效果就是将一个icon
drawable 对象染上在当前context对应主题中的
colorAccent属性的颜色.