2012-08-13 116 views
0

如何更改代码中按钮的状态。自从我从服务器获取图像后,我无法使用xml文件。从代码更改按钮的状态

使用:

Drawable d = new BitmapDrawable(getResources(),bitmap); 

我有提拉但我怎么分配不同的状态,然后将附加的按钮对应的图像?

+0

您的意思是由'国家':集中,按下,...? – iTurki 2012-08-13 19:45:13

+0

你是什么意思的“国家”?选择?重点?可见? – 0gravity 2012-08-13 19:45:18

+0

是正确聚焦,按下等。 – dejavu 2012-08-13 19:47:02

回答

1

在xml中,我们使用<selector>元素来做到这一点。在代码中,我们使用StateListDrawable

StateListDrawable content = new StateListDrawable(); 
Drawable pressedDrawable = new BitmapDrawable(getResources(),bitmap); 
//Your other drawables (focused, .....) 

content.addState(new int[] { android.R.attr.state_pressed }, pressedDrawable); 
//Add the other drawables the same way 

Button button = (Button) view.findViewById(R.id.my_button); 
button.setBackground(content); 
+0

但setImageDrawable未定义为按钮,是吗? – dejavu 2012-08-13 20:15:54

+1

我想它应该是button.setBackground(content); – dejavu 2012-08-13 20:32:30

+0

你说得对。我在我的代码中使用了'ImageButton',并且将其改为与您的代码匹配,但我忘记更改它。编辑。 – iTurki 2012-08-13 22:20:19