2010-06-21 5 views

Respuesta

19

En XML, se vería algo como esto:

style="?header_background" 

mediante programación, es un poco más difícil. En su actividad:

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

Y cuando se quiere acceder a un atributo del tema, que haría algo como esto:

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

Es un poco más complicado, pero hay que ir ;-)

+1

Esto realmente no funciona. typedvalueattr.resourceId siempre es 0. ¿Puede proporcionar un ejemplo completo de trabajo? – user123321

+1

Sabía que tenía que haber una manera sin saber qué tema se aplicaba actualmente. Funcionó perfecto! – DallinDyer

1

Lo anterior no es una buena forma de hacerlo por muchas razones. NullPointerExceptions es uno.

A continuación se muestra la forma correcta de hacerlo.

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

Luego de usar simplemente hacer:

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

Sólo asegúrese de que el contexto en el que se pasa en vino de la actividad. No haga getApplicationContext() o el tema devuelto será del objeto Aplicación y no de la Actividad.

0

Después de varias horas finalmente encontré una solución de trabajo, las anteriores solo devolvieron el archivo ressourceId, no el color. Se puede utilizar en su lugar:

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

Cambio ta.getColor(0, 0) con lo que se quiere conseguir, usted puede reemplazarlo con ta.getDimensionPixelSize(0, 0) por ejemplo. Si desea establecer un valor de retorno, reemplace el segundo 0 con el valor que necesite.

Cuestiones relacionadas