Android - getResources() and static

2019-06-18 23:24发布

问题:

I've got a class

public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener

out of this I try to call a method from another class. This method contains:

mFoo.setTextColor(getResources().getColor(R.color.orange))

But it doesn't work. It tells me getResources isn't static... how can I change this?

回答1:

But it doesnt work, it tells me, getResources isnt static... how can i change?

This means you are trying to call getResources() from a static method, rather than a regular (instance) method. The easiest thing to do in your case, if mFoo is a TextView or some other widget, is to call getResources() on the Context available from the widget:

mFoo.setTextColor(mFoo.getContext().getResources().getColor(R.color.orange));

However, the fact that you are trying to reference a widget named mFoo from a static method scares the crap out of me. This is just asking for a memory leak. I think you really need to reconsider your use of static data members and methods.