3

我想创建一个下拉颜色选择器,像这样(对不起丑陋的图像):

颜色下拉选择器

我只需要一些颜色(比如说 6 种),所以我不需要完整的颜色选择器,下拉菜单可以正常工作。

我知道我必须为 Spinner 扩展数组适配器并覆盖getDropDownViewgetView

我不知道的是如何创建一个带有边框和纯色背景的方形框。

我知道我可以在 drawable 中定义自己的形状。无论如何,我必须在运行时设置背景颜色,所以我还需要更改视图并设置正确的背景颜色。

最好的方法是什么?谢谢。

4

1 回答 1

6

如果您只想使用背景颜色,则可以像此示例一样使用。

public class CustomSpinnerAdapter<T extends BaseEntity> extends ArrayAdapter implements SpinnerAdapter {    

    private final List<T> objects; // android.graphics.Color list

    public CustomSpinnerAdapter(Context context, List<T> objects) {
        super(context, R.layout.yourLayout, objects);
        this.context = context;
        this.objects = objects;

    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        super.getDropDownView(position, convertView, parent);

        View rowView = convertView;


        if (rowView == null) {
            // Get a new instance of the row layout view
            LayoutInflater inflater = this.activity.getLayoutInflater();
            rowView = inflater.inflate(R.layout.yourLayout, null);

            rowView.setBackgroundColor(objects.get(position));

        } else {
            rowView.setBackgroundColor(objects.get(position));
        }


        return rowView;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowView = convertView;


        if (rowView == null) {
            // Get a new instance of the row layout view
            LayoutInflater inflater = this.activity.getLayoutInflater();
            rowView = inflater.inflate(R.layout.yourLayout, null);

            rowView.setBackgroundColor(objects.get(position));

        } else {
            rowView.setBackgroundColor(objects.get(position));
        }


        return rowView;
    }
}
于 2012-10-31T11:55:33.310 回答