Reset background color in a view

I am trying to restore the background color of a view.

I have several selected views. When the user clicks on one of these views, the following code is executed and the view turns 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 what color it was (I set it to Color.BLACK in the code above). I could not find getBackgroundColor or a similar method in the View class. If I had this, I could save the previous color and just return it when a new view is selected.

+4
source share
3 answers

use View. getBackground (), it returns the current "Drawable" background of the view, which can then be used in the view. setBackgroundDrawable ()

 View theView; Drawable originalBackground; ... originalBackground = theView.getBackground(); theView.setBackgroundColor(Color.YELLOW); ... theView.setBackgroundDrawable(originalBackground); 
+5
source

I'm not sure what you are trying to execute, but maybe a ColorStateList would be useful here .

+2
source

You can try to set the previous color as a view tag.

for instance

 View newSelection, previousSelection; newSelection.setTag(Color.Green); previousSelection.setTag(Color.Black); if(previousSelection != null) { previousSelection.setBackgroundColor((int)previousSelection.getTag()); } newSelection.setBackgroundColor(Color.YELLOW); 

I have not tried the code if there is an error, but there is a stream on how to implement it.

0
source

All Articles