使用和获取Android的主题属性

参考文章:
Android,如何在代码中获取attr属性的值

1. layout布局文件中使用主题属性

很多时候,我们想引用主题中的属性(attr)。例如
- colorBackGround:activity默认背景
- listChoiceBackgroundIndicator:listView中item使用的背景selector

这些在layout文件中使用时很简单的,只需要?+ 属性的方式即可引用。例如android:background="?android:colorBackground"

2. 代码中获取主题属性的两种方式

2.1 方式1:obtainStyledAttributes(返回TypedArray)

但是如果想要在代码中使用,可以这么做:

private @ColorInt int getColorBackground() {
       int[] attrs = new int[] {android.R.attr.colorBackground};
       TypedArray typedArray = getActivity().obtainStyledAttributes(attrs);
       int color = typedArray.getColor(0, 0xfffafafa);
       typedArray.recycle();
       return color;
   }

2.2 方式2:resolveAttribute(返回TypedValue)

也有另外一种方式.

   public static int getColorBackground(){
           TypedValue typedValue = new TypedValue();
           // 第三个参数true,实际上我看不太懂是什么作用。
           // 猜测:传入的id可能是一个引用,是否要继续解析该引用。
           // 文档中这么描述:
           /*
           If true, resource references will be walked; if
                             false, <var>outValue</var> may be a
                             TYPE_REFERENCE.  In either case, it will never
                             be a TYPE_ATTRIBUTE.
           */
           context.getTheme().resolveAttribute(android.R.attr.colorBackground, typedValue, true);
           return typedValue.data;
       }

2.3 两种方式的区别

方式1无法直接获取到某个Style中的值,而且它所需要的第三个参数看不太懂,获取到的TypedValue的使用方式也看不太懂。

所以我更倾向于使用obtainStyledAttributes方法,比较直观。并且在自定义View中也经常使用。

2.4 两种方式结合来获取某个Style中的值

在参考文章Android,如何在代码中获取attr属性的值
中,演示了如何获取某个Style中的值。

例如获取TextAppearance.Large中的textSize。

<style name="TextAppearance.Large">
    <item name="android:textSize">22sp</item>
    <item name="android:textStyle">normal</item>
    <item name="android:textColor">?textColorPrimary</item>
</style>

获取方式如下,因为方式1无法直接获取到某个Style中的值,所以两种方式结合:

// 先使用方式1获取到textAppearanceLarge style的resId
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(android.R.attr.textAppearanceLarge, typedValue, true);

// 然后obtain这个Id
int[] attribute = new int[] { android.R.attr.textSize };
TypedArray array = getTheme().obtainStyledAttributes(typedValue.resourceId, attribute);
int textSize = array.getDimensionPixelSize(0, -1);
array.recycle();

2.5 obtainStyledAttributes方式获取某个Style中的值

而实际上单纯使用obtainStyledAttributes方法即可获取更加便利,并且直观:

int[] attr = new int[]{android.R.attr.textSize};
TypedArray array = getTheme().obtainStyledAttributes(android.R.style.TextAppearance_Large, attr);
int textSize = array.getDimensionPixelSize(0  , -1 );
array.recycle();

3. 总结

综上所述,我推荐使用obtainStyledAttributes方法!

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值