2011-10-21 36 views
0

我已经将一个ImageButton定义为由选择器(对多个不同状态使用多个图像)绘制。我需要在运行时改变按钮的外观。如何在Java中为不同状态设置Android ImageButton backgroundimage代码

我知道我可以使用“setBackgroundResource” - 但我已经将实际的背景资源作为选择器。我需要为选择器中使用的特定状态设置图像。

所以,我需要以某种方式获得选择器,然后设置图像?如果我只是调用“setBackgroundResource”,我认为这将取消整个选择器。

我该如何去做这件事?

+0

可能重复的[取代选择器图像编程](http://stackoverflow.com/questions/4697528/replace-selector-images-programmatically) – Brad

回答

1

当按钮改变状态时,我简单地更换了选择器,如下所示。最后相当简单。按钮的类中:的

StateListDrawable states = new StateListDrawable(); 
    states.addState(new int[] {-android.R.attr.state_pressed},getResources().getDrawable(R.drawable.button_normal)); 
    states.addState(new int[] {android.R.attr.state_pressed},getResources().getDrawable(R.drawable.button_pressed)); 

    this.setImageDrawable(states); 
    this.invalidate(); 
0

你可以得到StateListDrawable设置,可能通过铸造或getDrawable()getBackground()然后调用selectDrawable()返回Drawable

+0

“selectDrawable” 是未记录。假设我得到StateListDrawable - 我无法弄清楚如何从那里设置图像。 – Brad

+0

使用你想要选择的drawable的数字索引 –

+0

所以在I * select * drawable之后,我该如何改变它呢? – Brad

相关问题