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)

转载请附上本文地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容