有时候需要通过当前应用的Theme,来判断当前应用所处的环境。
可以通过在Theme中设置一些flag来实现。
1. 添加flag属性
在frameworks/base/core/res/res/values/attrs.xml的“<declare-styleable name="Theme">”中添加:
<declare-styleable name="Theme">
<!– flag to decide whether it is our theme –>
<attr name="myflag" format="boolean" />
…
</declare-styleable>
2.自定义Theme
在所需的应用中添加一下判断语句即可:
<style name="myTheme" parent="android:Theme.Light.NoTitleBar">
<item name="android:myflag">true</item>
…
</style>
3.在应用中获得flag
在所需的应用(设置了myTheme)中添加以下判断语句即可:
TypedArray ta = context.obtainStyledAttributes(
null, com.android.internal.R.styleable.Theme,
com.android.internal.R.attr.myflag,
0);
boolean flag = ta.getBoolean(
com.android.internal.R.styleable.Theme_myflag, false);
mFlagTheme = flag ? 1 : 0;
ta.recycle();
--------------------------------------
函数说明:
public obtainStyledAttributes ( set, int[] attrs, int defStyleAttr, int defStyleRes)Since:
Return a StyledAttributes holding the attribute values in set that are listed in attrs. In addition, if the given AttributeSet specifies a style class (through the "style" attribute), that style will be applied on top of the base attributes it defines.
Be sure to call StyledAttributes.recycle() when you are done with the array.
When determining the final value of a particular attribute, there are four inputs that come into play:
- Any attribute values in the given AttributeSet.
- The style resource specified in the AttributeSet (named "style").
- The default style specified by defStyleAttr and defStyleRes
- The base values in this theme.
Each of these inputs is considered in-order, with the first listed taking precedence over the following ones. In other words, if in the AttributeSet you have supplied <Button textColor="#ff000000">
, then the button’s text will always be black, regardless of what is specified in any of the styles.
- Returns a TypedArray holding an array of the attribute values. Be sure to call
when done with it.
获取dimen值
int padding = 5 * mContext.getResources().getDimensionPixelSize(
com.android.internal.R.dimen.one_dip);