How is it possible to create a spinner with images instead of text?

前端 未结 3 1009
遥遥无期
遥遥无期 2020-12-07 23:12

Given the code bellow, is it possible to have images instead of text in the array planets?

    Spinner s = (Spinner) findViewById(R.id.spinner);    
    Arra         


        
3条回答
  •  [愿得一人]
    2020-12-07 23:37

    I just needed a super easy solution for a fixed set of images in a spinner, so I did this:

    public class SimpleImageArrayAdapter extends ArrayAdapter {
    private Integer[] images;
    
    public SimpleImageArrayAdapter(Context context, Integer[] images) {
        super(context, android.R.layout.simple_spinner_item, images);
        this.images = images;
    }
    
    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getImageForPosition(position);
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getImageForPosition(position);
    }
    
    private View getImageForPosition(int position) {
            ImageView imageView = new ImageView(getContext());
            imageView.setBackgroundResource(images[position]);
            imageView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            return imageView;
    }
    

    }

    And then in the code you can just use it like this:

        SimpleImageArrayAdapter adapter = new SimpleImageArrayAdapter(context, 
            new Integer[]{R.drawable.smiley1, R.drawable.smiley2, R.drawable.smiley3, R.drawable.smiley4, R.drawable.smiley5});
        spinner.setAdapter(adapter);
    

提交回复
热议问题