如何使用StateListDrawable(动态或编程或通过代码)将图像设置为按钮的背景

时间:2012-06-21 05:31:48

标签: android android-layout

这是我的代码:

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文件。我无法弄明白我的代码错误或我必须指定额外属性... :(

1 个答案:

答案 0 :(得分:6)

@KK你正确地做了一些错误

查看我的代码

public void selector(Button b,int pressed_image,int normal_image )
    {
        StateListDrawable states = new StateListDrawable();
        states.addState(new int[] { android.R.attr.state_pressed }, getResources().getDrawable(pressed_image));
        states.addState(new int[] {}, getResources().getDrawable(normal_image));
        b.setBackgroundDrawable(states);
    }

你可以说这段代码与你的代码相同,但有一些区别。 我在states.addState(new int[] { android.R.attr.state_pressed }, getResources().getDrawable(pressed_image));

之前写了states.addState(new int[] {}, getResources().getDrawable(normal_image));

首先尝试这段代码,我已经测试了这段代码4-5次,然后在这里发布。我真的不知道为什么改变行代码工作正常。