Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

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

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

    Spinner s = (Spinner) findViewById(R.id.spinner);    
    ArrayAdapter adapter = ArrayAdapter.createFromResource(            
            this, R.array.planets, android.R.layout.simple_spinner_item);    
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
    s.setAdapter(adapter);

and

    <string name="planet_prompt">Choose a planet</string>
    <string-array name="planets">        
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>        
        <item>Mars</item>        
        <item>Jupiter</item>        
        <item>Saturn</item>        
        <item>Uranus</item>        
        <item>Neptune</item>    
    </string-array>    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<Integer> {
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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...