Das oben genannte ist keine gute Möglichkeit, dies aus vielen Gründen zu tun. NullPointerExceptions ist eins.
Unten ist der richtige Weg, dies zu tun.
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;
}
}
Dann tun zu verwenden, nur:
final int attribColor = ThemeUtils.getStyleAttribColorValue(context, R.attr.some_attr, 0x000000 /* default color */);
Nur der Kontext stellen Sie sicher, dass Sie in der Aktivität kam passieren. Tun Sie nicht getApplicationContext() oder das zurückgegebene Theme stammt vom Anwendungsobjekt und nicht von der Aktivität.
Dies funktioniert nicht wirklich. typedvalueattr.resourceId ist immer 0. Können Sie ein vollständiges Arbeitsbeispiel angeben? – user123321
Ich wusste, dass es einen Weg geben musste, ohne zu wissen, welches Thema gerade angewendet wurde. Perfekt gearbeitet! – DallinDyer