如何在Spinner中添加图像?

时间:2014-07-09 13:50:56

标签: android drop-down-menu spinner

我制作了这款名为UnitConverter的应用......

    unitarray=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item);
    unitarray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    SpinnerUnit.setAdapter(unitarray);
    unitarray.add(getResources().getString(R.string.unit1));
    unitarray.add(getResources().getString(R.string.unit2));
    unitarray.add(getResources().getString(R.string.unit3));
    unitarray.add(getResources().getString(R.string.unit4));
    unitarray.add(getResources().getString(R.string.unit5));
    unitarray.add(getResources().getString(R.string.unit6));
    unitarray.add(getResources().getString(R.string.unit7));
    unitarray.add(getResources().getString(R.string.unit8));
    unitarray.setNotifyOnChange(true);

一切都很棒但是我想把图像放在每个单元旁边! 请问有谁可以帮我这个吗?谢谢!

1 个答案:

答案 0 :(得分:0)

最简单的方法可能是使用android的R.layout.simple_spinner_item作为微调元素布局,并在内部使用setCompoundDrawablesWithIntrinsicBounds

将图像添加到TextView


ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_spinner_item, countries);
countrySpinner.setAdapter(adapter);



适配器:


class ImageSpinnerAdapter extends ArrayAdapter {
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView textView = (TextView) super.getView(position, convertView, parent);
        Elem elem = elemArray.get(position);
        textView.setText(elem.toString());
        textView.setCompoundDrawablesWithIntrinsicBounds(elem.getImage(), null, null, null);
        return textView;
    }
}


查看详细示例here.