Android的 - 从code参考在当前应用的主题属性的值属性、主题、Android、code

2023-09-05 03:31:32 作者:我造你?我宣你i

在Android devGuide 解释它是如何可能引用在当前应用的主题属性的值,使用问号(?)而不是在(@)。

the Android devGuide explains how it is possible to reference the value of an attribute in the currently-applied theme, using the question-mark (?) instead of at (@).

有谁知道如何从code,如做到这一点在定制组件?​​

Does anyone know how to do this from code, e.g. in a customized component?

推荐答案

在XML中,它看起来是这样的:

In XML, it would look something like this:

style="?header_background"

编程,这是一个有点麻烦。在您的活动:

programmatically, it's a little trickier. In your activity:

private static Theme theme = null;

protected void onCreate(Bundle savedInstanceState) {
   ...
   theme = getTheme();
   ...
}

public static int getThemeColors(int attr){
   TypedValue typedvalueattr = new TypedValue();
   theme.resolveAttribute(attr, typedvalueattr, true);
   return typedvalueattr.resourceId;
}

而当你想要访问主题的属性,你会做这样的事情:

And when you want to access an attribute of the theme, you would do something like this:

int outside_background = MyActivity.getThemeColors(R.attr.outside_background);
setBackgroundColor(getResources().getColor(outside_background));

这是一个有点比较绕口,但你去那里; - )

It's a little more convoluted, but there you go ;-)

 
精彩推荐