9

I have some resources defined, e.g.:

<color name="lightGrey">#FFCCCCCC</color>
<integer name="KEY_POSITION_ARM">2</integer>

...and I have an ArrayAdapter displaying items to TextViews. I'm trying to access the values with code like:

keyPosition = getResources().getInteger(R.integer.KEY_POSITION_ARM);
moduleDataView.setTextColor(getResources().getColor(R.color.darkgreen));

...but I get errors like "The method getResources() is undefined for the type ContinuityAdapter". (ContinuityAdapter extends ArrayAdapter)

Is there a good way around this?

Thanks

This is an example:

switch (currentModule.keyPosition) {
case activity.getResources().getInteger(R.integer.KEY_POSITION_ARM):
    moduleDataView.keyPosition.setText("TEST");
    moduleDataView.keyPosition.setTextColor(Color.GREEN);
    break;
case R.integer.KEY_POSITION_ARM:
    moduleDataView.keyPosition.setText("ARM");
    moduleDataView.keyPosition.setTextColor(Color.RED);
    break;
}

The first case give an error, and the second doesn't but doesn't use the value from the XML file either. Although as you say I can just use the R... value as long as I use it that way everywhere. Just not sure if this is considered 'best practice'. Thanks

ARQuattr
  • 93
  • 1
  • 1
  • 5

1 Answers1

26

You need a Context object to call Context.getResources() method. Usually you can pass a Context or its subclass (i.e. Activity) through the constructor of your custom adapter.

Like:

public ContinuityAdapter extends ArrayAdapter {
    private final Context mContext;
    ...
    public ContinuityAdapter(Context context) {
        mContext = context;
    }
}

and then use:

mContext.getResources()...

Edit: This seem to be the case to avoid switch. See:

Community
  • 1
  • 1
user802421
  • 7,465
  • 5
  • 40
  • 63
  • Thanks. I had tried it and I thought it didn't work, but now I realize that I was getting another error doing: 'switch (foo) { case activity.getResources().getInteger(R.integer.KEY_POSITION_ARM):' The case statement obviously requires a constant expression, even though the resource is constant. Am I stuck using if statements? – ARQuattr Nov 21 '11 at 21:39
  • I need to see more code. Generally I tried to avoid switch cases or I use the resource id directly (i.e. case R.id.xyz). – user802421 Nov 21 '11 at 22:59
  • I edited the question to include a better code example. Thanks – ARQuattr Nov 22 '11 at 02:41