2014-04-27 4 views
8

पर आधारित एटआर रंग मान प्राप्त करें मेरी गतिविधि में मैं रख रहा हूं, जिसमें मैं थीम सेट कर रहा हूं।वर्तमान सेट थीम

public class SuperActivity extends Activity { 
@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setTheme(R.style.MyTheme); 
    } 
} 

themes.xml

<!-- ImageBackround --> 
<style name="Theme.MyTheme" parent="ThemeLight"> 
    <item name="myBgColor">@color/translucent_black</item> 
</style> 

अब मैं अपने बच्चे गतिविधि का एक में इस रंग लाने के लिए चाहते हैं।

इस संभावित answer में उल्लेख किया है, मैं ने लिखा है:

int[] attrs = new int[] { R.attr.myBgColor /* index 0 */}; 
TypedArray ta = ChildActivity.this.obtainStyledAttributes(attrs); 
int color = ta.getColor(0, android.R.color.background_light); 
String c = getString(color); 
ta.recycle(); 

लेकिन हर मैं android.R.color.background_light & R.attr.myBgColor की नहीं का डिफ़ॉल्ट मान का मूल्य हो रही है।

जहां मैं गलत कर रहा हूं। क्या मैं ChildActivity.this के गलत संदर्भ को पार कर रहा हूं?

उत्तर

7

आप दो संभव समाधान (एक क्या आप वास्तव में है, लेकिन मैं पूर्णता के लिए के लिए दोनों शामिल हैं):

TypedValue typedValue = new TypedValue(); 
if (context.getTheme().resolveAttribute(R.attr.xxx, typedValue, true)) 
    return typedValue.data; 
else 
    return Color.TRANSPARENT; 

या

int[] attribute = new int[] { R.attr.xxx }; 
TypedArray array = context.getTheme().obtainStyledAttributes(attribute); 
int color = array.getColor(0, Color.TRANSPARENT); 
array.recycle(); 
return color; 

Color.TRANSPARENT यकीन के लिए किसी अन्य डिफ़ॉल्ट हो सकता है । और हाँ, जैसा कि आपको संदेह है, संदर्भ बहुत महत्वपूर्ण है। यदि आप वास्तविक के बजाय डिफ़ॉल्ट रंग प्राप्त करते रहें, तो जांचें कि आप किस संदर्भ में जा रहे हैं। मुझे इसे समझने में कई घंटे लग गए, मैंने कुछ टाइपिंग को छोड़ने की कोशिश की और बस getApplicationContext() का उपयोग किया लेकिन इसे रंग नहीं मिला ...

+0

अंत में, एक जवाब जो बॉक्स से बाहर काम करता है! – kirtan403

संबंधित मुद्दे