如何在代码中获取attr属性的值

本文介绍如何在Android中通过代码获取XML定义的attr属性值,包括颜色、尺寸等,并展示了如何处理样式属性值,提供了实际应用场景示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何在代码中获取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() 方法回收资源。

Android 源码中的使用实例

Drawable drawable = context.getPackageManager()
.getResourcesForApplication(tile.iconPkg).getDrawable(tile.iconRes, null);
if (!tile.iconPkg.equals(context.getPackageName()) && drawable != null) {
    // If this drawable is coming from outside Settings, tint it to match the color.
    TypedValue tintColor = new TypedValue();
    context.getTheme().resolveAttribute(com.android.internal.R.attr.colorAccent,
    tintColor, true);
    drawable.setTint(tintColor.data);
}
tileIcon.setImageDrawable(drawable);
上面的代码是在Android M设置中的拷贝出来的代码,这个效果就是将一个icon  drawable 对象染上在当前context对应主题中的 colorAccent属性的颜色.
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值