如何从代码中更改按钮的状态。我无法使用xml文件,因为我从服务器获取图像。
使用:
Drawable d = new BitmapDrawable(getResources(),bitmap);
我有drawable但是如何分配不同的状态然后为按钮添加相应的图像?
答案 0 :(得分: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);