Custom spinner with object ArrayAdapter can't

2019-07-23 05:39发布

问题:

I am using the tutorial here to create a custom spinner. When I copy the class CountryAdapter (half-way down the page), eclipse is not able to identify getResources() in

myFlag.setBackgroundDrawable(getResources().getDrawable(item.getCountryFlag()));

Does anyone know a fix to this problem? Basically, how else might I get the drawable? I am copying the class below

public class CountryAdapter extends ArrayAdapter<CountryInfo>
    {
        private Activity context;
        ArrayList<CountryInfo> data = null;

        public CountryAdapter(Activity context, int resource, ArrayList<CountryInfo> data)
        {
            super(context, resource, data);
            this.context = context;
            this.data = data;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) 
        {   // Ordinary view in Spinner, we use android.R.layout.simple_spinner_item
            return super.getView(position, convertView, parent);   
        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent)
        {   // This view starts when we click the spinner.
            View row = convertView;
            if(row == null)
            {
                LayoutInflater inflater = context.getLayoutInflater();
                row = inflater.inflate(R.layout.spinner_layout, parent, false);
            }

            CountryInfo item = data.get(position);

            if(item != null)
            {   // Parse the data from each object and set it.
                ImageView myFlag = (ImageView) row.findViewById(R.id.imageIcon);
                TextView myCountry = (TextView) row.findViewById(R.id.countryName);
                if(myFlag != null)
                {
                    myFlag.setBackgroundDrawable(getResources().getDrawable(item.getCountryFlag()));
                }
                if(myCountry != null)
                    myCountry.setText(item.getCountryName());

            }

            return row;
        }
    }
}

回答1:

The getResources() method is not available in the ArrayAdapter class, it actually comes from the Context (in this case your Activity class, as it extends Context). Since you've got a reference to the Activity, try using context.getResources() instead.