उपरोक्त कई कारणों से ऐसा करने का एक अच्छा तरीका नहीं है। 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 */);
बस सुनिश्चित करें कि संदर्भ है कि आप में से पारित गतिविधि से आया हो। GetAplicationContext() नहीं मिलता है या वापस दिया गया थीम एप्लिकेशन ऑब्जेक्ट से होगा, न कि गतिविधि।
स्रोत
2015-05-19 18:47:11
यह वास्तव में काम नहीं करता है। typedvalueattr.resourceId हमेशा 0 है। क्या आप एक पूर्ण कार्य उदाहरण प्रदान कर सकते हैं? – user123321
मुझे पता था कि वर्तमान में कौन सी थीम लागू की गई थी, यह जानने के बिना एक तरीका होना था। सही काम किया! – DallinDyer