获取自定义属性通常是在自定义View内部获取,但在某种方式下,无论自定义View的属性还是主题中样式的属性,均可在外部style中获取。
由于非自定义View的外部获取方式比较复杂,这里暂时略过,后续补充。
自定义attr
设置attr
@string/theme_name_1
获取
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,outValue, true);
textView.setBackgroundResource(outValue.resourceId);
注意,如果我直接设置数据,则resourceId为0
我的主题
这时候我们的数据可以使用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;
}
原文:http://my.oschina.net/ososchina/blog/499147