How to dynamically populate Android spinner with text + image

前端 未结 3 968
情话喂你
情话喂你 2020-12-01 21:04


This is what i am trying to achieve                 I am able to a

3条回答
  •  盖世英雄少女心
    2020-12-01 21:24

    Try this

    This is the simplest way of creating a spinner with text and images both.

    1. Create a new layout inside res/layout/ with any name e.g. spinner_value_layout.xml

      
      
      
          
          "
      
      

    2. Create a new class SimpleImageArrayAdapter

       public class SimpleImageArrayAdapter extends ArrayAdapter {
       private Integer[] images;
       private String[] text;
       private Context context;
      
       public SimpleImageArrayAdapter(Context context, Integer[] images,String[] text) {
         super(context, android.R.layout.simple_spinner_item, images);
         this.images = images;
         this.text=text;
         this.context=context;
       }
      
       @Override
       public View getDropDownView(int position, View convertView, ViewGroup parent) {
          return getImageForPosition(position, convertView, parent);
       }
      
       @Override
       public View getView(int position, View convertView, ViewGroup parent) {
           return getImageForPosition(position, convertView, parent);
       }
      
       private View getImageForPosition(int position, View convertView, ViewGroup parent) {
          LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
          View row = inflater.inflate(R.layout.spinner_value_layout, parent, false);
          TextView textView = (TextView) row.findViewById(R.id.spinnerTextView);
          textView.setText(text[position]);
          ImageView imageView = (ImageView)row.findViewById(R.id.spinnerImages);
          imageView.setImageResource(images[position]);
          return row;
         }
      
    3. and finally use this at your class where you are passing id of spinner

       Integer[] integers=new Integer[]{R.drawable.ic_launcher_foreground, R.drawable.ic_launcher_background};
       String[] strings=new String[]{"foreground","background"};
      SimpleImageArrayAdapter adapter = new 
      SimpleImageArrayAdapter(getApplicationContext(),integers,strings);
        spinner.setAdapter(adapter);
      

    Output:-

提交回复
热议问题