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)

原文: http://solo.farbox.com/blog/how-to-get-value-of-attr-in-code

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值