天天看點

Android,如何在代碼中擷取attr屬性的值擷取arrt的值擷取arrt樣式中的值最後

擷取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( /* index */, - /* default size */);
array.recycle();
           

注意,要記得調用TypedArray.recycle()方法回收資源。

最後

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

getValueOfColorAttr(int attr)

getValueOfTextSizeAttr(int style, int value)

轉自:http://solo.farbox.com/blog/how-to-get-value-of-attr-in-code#toc_0