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

标签 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 文件。我无法弄清楚我的代码哪里错了或者我必须指定额外属性的地方......:(

最佳答案

@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 次,然后在这里发布。我真的不知道为什么更改行代码可以正常工作。

关于android - 如何使用 StateListDrawable 将图像设置为按钮的背景(动态或以编程方式或通过代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11132047/

相关文章:

android - 如何不回收我的 recyclerview 或任何项目的前 2 个 View ?

android - 在 ConstraintLayout 的可见性设置为 View.GONE 后恢复 View

android - 由于 NullPointerException 无法启动 Activity

android - 在 4k 屏幕上的 WebView 中显示的内容似乎分辨率很低

java - 减去和比较日期

android - findViewById 错误

android - 如何在 Canvas 的右下角绘制小标志类型的图像?

Android Asus 七寸 hdpi 平板布局问题

android - 使用 AChartEngine 库的条形图

android - 带工具栏的 Viewpager