views:

64

answers:

2

I'm trying to restore the background Color of a View.

I have several selectable Views. When the user clicks one of those Views, the following code is executed and the View becomes Yellow:

View newSelection, previousSelection;

...

if(previousSelection != null) {
    previousSelection.setBackgroundColor(Color.BLACK); // problem here
}
newSelection.setBackgroundColor(Color.YELLOW);

However, I want to reset the color of the previously selected View. However, I do not know which color it was (I'm setting it to Color.BLACK in the above code). I was not able to find a getBackgroundColor or similar method in the View class. If I had it, I could save the previous color and just put it back when the new View is selected.

+2  A: 

I'm not sure exactly what you are trying to accomplish but perhaps a ColorStateList would come in handy here.

schwiz
A: 

You can try setting the previous color as a tag of the view.

For example

View newSelection, previousSelection;

newSelection.setTag(Color.Green);
previousSelection.setTag(Color.Black);

if(previousSelection != null) {
    previousSelection.setBackgroundColor((int)previousSelection.getTag());
}
newSelection.setBackgroundColor(Color.YELLOW);

I haven't tried the code if there is an error but the flow on how to implement is there.

M.A. Cape
The problem is that I do not know the original color of the View.
MyNameIsZero
Are you not the one setting the original color of the view?
M.A. Cape
I'm not setting the original color because the original color is the default color used by android when no color is specified.
MyNameIsZero
Then you should set it yourself. I suggest create a colorstatelist just like schwiz said. It is an xml file that contains colors depending on the state of a view. Just set it as the background of the view. By the way, can you try to elaborate more what you want to accomplish so that we can help you.
M.A. Cape