Custom spinner with object ArrayAdapter can't getResources

那年仲夏 提交于 2020-01-06 02:50:18

问题


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.



来源:https://stackoverflow.com/questions/16094457/custom-spinner-with-object-arrayadapter-cant-getresources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!