In my ArrayAdapter class I capture the context passed in. Then int the getView method, I have this if statement:
if(m.getSide() == RED) {
v.setBackgroundColor(lc.getResources().getColor(R.color.red_bouy));
Log.d("MA", "HERE");
} else if(m.getSide() == BLACK) {
v.setBackgroundColor(lc.getResources().getColor(R.color.black_bouy));
}
(lc is the Context I grab from the Constructor)
If I just use Color.red, it works find. All examples I've seen use ghet getResources..., but from within an activity.
Any suggestions?
When you create adapter, you pass a Context to constructor. In getView() you can call getContext().getResources().get... Is this what you were looking for?
Also, @MahdeTo is right: you seem to keep a live reference to context - don't! You'll leak your context. If you absolutely must, use WeakReference<Context> and check for null, but I don't see why you would have to.
UPD: Not really a problem with Adapter
s (tnx to @Arhimed and @Rperryng for pointing this out) since their proper usage ensures their lifecycle doesn't exceed that of their Context
, so it's ok to store a live link to a Context
[even if the adapter itself has a live ref in the Context
-- GC is pretty smart, isn't fooled by circular refs]. Nevertheless, there's no need to do that in this case: ArrayAdapter.getContext()
is there for this exact purpose - so you can access resources and get an Inflater
when you need one to build views in getView()