获取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()
方法回收资源。
最后
看上去挺烦锁的,实际上应该是傻瓜思维,根据不同方法直接获取,例如:
getValueOfColorAttr(int attr) getValueOfTextSizeAttr(int style, int value)
---------------------------------------------------------------------------------------------------------------------------------------
Android: how to get value of “listPreferredItemHeight” attribute in code?
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(attr, outValue, true);
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outValue.getDimension(outMetrics);
转自:http://solo.farbox.com/blog/how-to-get-value-of-attr-in-code