android获取自定义属性,Android 主题样式中的自定义属性值的获取方式

获取自定义属性通常是在自定义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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值