您的位置:首页 > 移动开发 > Android开发

使用和获取Android的主题属性

2018-01-24 12:02 459 查看
参考文章:

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方法!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: