2010-06-21 48 views
9

中Android Android devGuide explains中当前应用的主题中属性的值如何使用问号(?)代替当前应用的主题中引用属性的值的方式(@)。Android - 引用代码

有谁知道如何从代码中做到这一点,例如在一个定制的组件?

回答

19

在XML中,它会是这个样子:

style="?header_background" 

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

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; 
} 

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

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

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

+1

这实际上不起作用。 typedvalueattr.resourceId始终为0.您能提供一个完整的工作示例吗? – user123321 2011-12-15 06:07:02

+1

我知道必须有一种方式不知道当前应用了哪个主题。工作完美! – DallinDyer 2013-04-19 14:35:51

1

上述不是一个很好的方法来做这件事,原因很多。 NullPointerExceptions是一个。

下面是这样做的正确方法。

public final class ThemeUtils { 
    // Prevent instantiation since this is a utility class 
    private ThemeUtils() {} 

    /** 
    * Returns the color value of the style attribute queried. 
    * 
    * <p>The attribute will be queried from the theme returned from {@link Context#getTheme()}.</p> 
    * 
    * @param context the caller's context 
    * @param attribResId the attribute id (i.e. R.attr.some_attribute) 
    * @param defaultValue the value to return if the attribute does not exist 
    * @return the color value for the attribute or defaultValue 
    */ 
    public static int getStyleAttribColorValue(final Context context, final int attribResId, final int defaultValue) { 
     final TypedValue tv = new TypedValue(); 
     final boolean found = context.getTheme().resolveAttribute(attribResId, tv, true); 
     return found ? tv.data : defaultValue; 
    } 
} 

然后使用只是做:

final int attribColor = ThemeUtils.getStyleAttribColorValue(context, R.attr.some_attr, 0x000000 /* default color */); 

只要确保你通过在上下文从活动来了。不要执行getApplicationContext(),或者返回的主题将来自Application对象而不是Activity。

0

几个小时后,我终于找到了一个工作解决方案,上面的只返回了ressourceId,而不是颜色。您可以使用它代替:

public static int getThemeColor(Context context, int attr) { 
    TypedValue typedValue = new TypedValue(); 
    context.getTheme().resolveAttribute(attr, typedValue, true); 
    TypedArray ta = context.obtainStyledAttributes(typedValue.resourceId, new int[]{attr}); 
    int color = ta.getColor(0, 0); 
    ta.recycle(); 
    return color; 
} 

变化ta.getColor(0, 0)与你想要得到的东西,你可以用ta.getDimensionPixelSize(0, 0)例如更换。如果您想设置回退值,请将第二个0替换为您需要的任何值。