Android,如何在代碼中獲取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()方法回收資源。

最后

看上去挺煩鎖的,實際上應該是傻瓜思維,根據不同方法直接獲取,例如:

getValueOfColorAttr(int attr)
getValueOfTextSizeAttr(int style, int value)

轉載請附上本文地址

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容