重置视图的背景颜色

时间:2010-09-08 19:49:53

标签: android view background-color

我正在尝试恢复视图的背景颜色。

我有几个可选择的视图。当用户单击其中一个视图时,将执行以下代码并且视图变为黄色:

View newSelection, previousSelection;

...

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

但是,我想重置以前选择的视图的颜色。但是,我不知道它是哪种颜色(我在上面的代码中将它设置为Color.BLACK)。我无法在View类中找到getBackgroundColor或类似的方法。如果我拥有它,我可以保存以前的颜色,并在选择新视图时将其放回。

3 个答案:

答案 0 :(得分:5)

使用View。 getBackground (),它返回视图的当前“Drawable”背景,然后可以在View中使用。 setBackgroundDrawable ()

View theView;
Drawable originalBackground;

...

originalBackground = theView.getBackground();

theView.setBackgroundColor(Color.YELLOW);

...
theView.setBackgroundDrawable(originalBackground);

答案 1 :(得分:2)

我不确定你想要完成什么,但也许ColorStateList会派上用场。

答案 2 :(得分:0)

您可以尝试将以前的颜色设置为视图的标记。

例如

View newSelection, previousSelection;

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

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

如果出现错误,我还没有尝试过代码,但有关如何实现的流程就在那里。

相关问题