獲取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)