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.
Esto realmente no funciona. typedvalueattr.resourceId siempre es 0. ¿Puede proporcionar un ejemplo completo de trabajo? – user123321
Sabía que tenía que haber una manera sin saber qué tema se aplicaba actualmente. Funcionó perfecto! – DallinDyer