user963313
user963313

Reputation: 79

How to create list of color on Java, Android?

I need to create Spinner for list of colors. I will take selected item, get selected color and set this color for another elements. I want to set list of colors in .xml, because I have a few spinners, and want to create resource for it. But if I create a simple list of key -pair , in code I have to create many blocks (if else) for checking colors. How can I create and use resource file (pairs "string-int") for spinner? Thank you

Upvotes: 2

Views: 5341

Answers (2)

Kartik Domadiya
Kartik Domadiya

Reputation: 29968

You already know how you are displaying data in Spinner.

Take String Array for displaying the data in Spinner.

Consider String[] array={"Green","Blue","Red"};

Now take one other array for colors such that it matches the color in the first array..

Here there are 2 options viz. String or int Array

String Array => String[] arrayColors={"#00ff00","#0000ff","#ff0000"};

int Array => int [] arrayColors={Color.GREEN,Color.BLUE,Color.Red}

Use any one. (Recommended : use int Array because you dont have to parse the color when using it)

So you establish One-to-One correspondence between both arrays.

Now register for OnItemSelectedListener listener for listening to selection in Spinner

yourSpinner.setOnItemSelectecListener(new OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view,
            int pos, long id) {
        // Change color of other views by using pos argument

        // IF YOU HAVE USED String Array
        yourView.setBackgroundColor(Color.parseColor(arrayColors[pos]));

        // IF YOU HAVE USED int Array
        yourView.setBackgroundColor(arrayColors[pos]);
    }

    public void onNothingSelected(AdapterView parent) {
        // Do nothing.
    }
});

Upvotes: 6

Nuno Gon&#231;alves
Nuno Gon&#231;alves

Reputation: 6815

Doesn't something like this help?

String[] colorList = {"white", "black"};
int[] color = {Color.WHITE, Color.BLACK};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, colorList );  

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
modeSpinner.setAdapter(adapter);

modeSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
    {
        yourView.setColor(color.get(colorList.getSelectedItemPosition())                
    }
    public void onNothingSelected(AdapterView<?> arg0) 
    {
    //...
    }
});

Upvotes: 1

Related Questions