开发者

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开发者_StackOverflow -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


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.
    }
});


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) 
    {
    //...
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜