1
这是我的代码:如何设置的图像作为背景使用StateListDrawable(动态或程序或通过代码)一个按钮
public void setHoverEffect(final Button button,int normalImageId, int hoverImageId) {
if (button != null)
{
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[]{ }, getResources().getDrawable(normalImageId));
stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, getResources().getDrawable(hoverImageId));
button.setBackgroundDrawable(stateListDrawable);
}
}
当我使用上面的代码只有正常图像被显示为背景当我按下按钮时,它不显示悬停图像。
当我使用selector.xml
文件,如下图所示,并设置为背景,做工精细。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/btn_ok_h"> </item>
<item android:drawable="@drawable/btn_ok"> </item>
</selector>
我想动态地做到这一点,以避免为我的应用程序中的每个按钮创建选择器XML文件。我想不出它在哪里我的代码错了或者我必须指定额外的属性... :(
感谢ü非常........................................... ..............................你让我的一天........... :) :) –
顺序是不同的。视图将匹配符合当前视图状态的第一个可绘制状态 – jerry