如何将图像设置为使用StateListDrawable(动态或程序,或通过code)背景的一个按钮设置为、如何将、按钮、图像

2023-09-06 16:08:26 作者:时间会让俄淡忘°

下面是我的code:

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);
        }
}

当我只用正常的图像显示为背景,当我preSS的按钮,它没有显示悬停形象。上述code

When I use the above code only the normal image is appearing as background and when I press the button it is not showing the hover image.

当我使用如下图所示的 selector.xml 文件,并将它设置为背景的它工作正常。

When I use the selector.xml file as shown below and set it as background it working fine.

<?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文件中的每一个按钮,在我的应用程序动态地做到这一点。我无法算出它在我的code是错误的或者我必须指定额外的属性... :(

I want to do this dynamically in order to avoid creating selector xml file for each and every button in my application. I can't figure it out where my code was wrong or where I have to specify extra attributes... :(

推荐答案

@KK你正在做正确的方式与一些错误

@KK you are doing right way with some mistake

看我的code

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);
    }

你可以说这code是与您的code,但也有一些差别。我已经写了 states.addState(新INT [] {android.R.attr.state_ pressed},getResources()getDrawable(pressed_image)); states.addState线(新INT [] {},getResources()getDrawable(normal_image));

第一次尝试这个code,我测试了这个code 4-5次,然后张贴在这里。我真的不知道为什么变线code正常工作。

First try this code, I have tested this code 4-5 times and then post here. I really don't know why changing line code working fine.