Question

I would like to have a list of colors in a spinner, how can I do? I do not want to store the RGB code in a database, you can do it directly from XML? Which way you recommend?

Was it helpful?

Solution

You can use a custom Adapter like this:

private class ExampleAdapter extends ArrayAdapter<String> {

    private final int[] colors = new int [] {
            Color.WHITE,
            Color.RED,
            Color.BLUE
    };

    private ExampleAdapter(Context context, int resource) {
        super(context, resource);
    }

    private ExampleAdapter(Context context, int resource, int textViewResourceId) {
        super(context, resource, textViewResourceId);
    }

    public ExampleAdapter(Context context, int resource, String[] objects) {
        super(context, resource, objects);
    }

    private ExampleAdapter(Context context, int resource, int textViewResourceId, String[] objects) {
        super(context, resource, textViewResourceId, objects);
    }

    private ExampleAdapter(Context context, int resource, List<String> objects) {
        super(context, resource, objects);
    }

    private ExampleAdapter(Context context, int resource, int textViewResourceId, List<String> objects) {
        super(context, resource, textViewResourceId, objects);
    }

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

        int color = getColorForPosition(position);
        view.setBackgroundColor(color);

        return view;
    }

    private int getColorForPosition(int position) {
        return colors[position % colors.length];
    }
}

You would use this ExampleAdapter like you would use any ArrayAdapter but the items will cycle through the background colors defined at the top.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top