標籤:
擷取自訂屬性通常是在自訂View內部擷取,但在某種方式下,無論自訂View的屬性還是主題中樣式的屬性,均可在外部style中擷取。
由於非自訂View的外部擷取方式比較複雜,這裡暫時略過,後續補充。
自訂attr
<?xml version="1.0" encoding="utf-8"?><resources xmlns:android="http://schemas.android.com/apk/res/android"> <attr name="theme_name" format="string|reference"/></resources>
設定attr
<resources> <!-- Activity themes --> <style name="Theme.Base" parent="android:Theme.Holo.Light" > <item name="theme_name" >@string/theme_name_1</item> </style></resources>
擷取
TypedValue outValue = new TypedValue();getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,outValue, true);textView.setBackgroundResource(outValue.resourceId);
注意,如果我直接設定資料,則resourceId為0
<resources> <!-- Activity themes --> <style name="Theme.Base" parent="android:Theme.Holo.Light" > <item name="theme_name" >我的主題</item> </style></resources>
這時候我們的資料可以使用TypeValue.string讀取
TypedValue outValue = new TypedValue();getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,outValue, true);if(outValue.data==TypeValue.TYPE_STRING){textView.setBackgroundResource(outValue.string);}
當然,有時候我們的屬性可能是個集合,這時候不能用TypedValue擷取,TypeValued只能判斷類型,因此我們選擇如下方式
public int getTabContainerHeight() { TypedArray a = mContext.obtainStyledAttributes(null, android.support.v7.appcompat.R.styleable.ActionBar, android.support.v7.appcompat.R.attr.actionBarStyle, 0); int height = a.getLayoutDimension(android.support.v7.appcompat.R.styleable.ActionBar_height, 0); Resources r = mContext.getResources(); if(!hasEmbeddedTabs()) height = Math.min(height, r.getDimensionPixelSize(android.support.v7.appcompat.R.dimen.abc_action_bar_stacked_max_height)); a.recycle(); return height; }
對於View內部擷取方式如下
private static Context themifyContext(Context context, AttributeSet attrs, int defStyleAttr) { TypedArray a = context.obtainStyledAttributes(attrs, android.support.v7.appcompat.R.styleable.Toolbar, android.support.v7.appcompat.R.attr.ActionBarStyle, 0); int themeId = a.getResourceId(android.support.v7.appcompat.R.styleable.Toolbar_theme, 0); if(themeId != 0) context = new ContextThemeWrapper(context, themeId); a.recycle(); return context; }
Android 主題樣式中的自訂屬性值的擷取方式