Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting access to resources from an ArrayAdapter in Android

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

like image 354
ARQuattr Avatar asked Nov 21 '11 19:11

ARQuattr


People also ask

What is use of ArrayAdapter in Android?

You can use this adapter to provide views for an AdapterView , Returns a view for each object in a collection of data objects you provide, and can be used with list-based user interface widgets such as ListView or Spinner .

What parameters does ArrayAdapter take?

Parameters. The current context. This value can not be null. The resource ID for the layout file containing a layout to use when instantiating views.

Which is the 3rd argument for ArrayAdapter?

The third parameter is textViewResourceId which is used to set the id of TextView where you want to display the actual text. Below is the example code in which we set the id(identity) of a text view.


1 Answers

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:

  • Ways to eliminate switch in code
  • Alternative to Switch Case in Java
  • How to avoid long switch-case statements?
like image 178
user802421 Avatar answered Oct 06 '22 09:10

user802421