ImageButton 颜色不改变 onPressed(), onFocus()

标签 imagebutton android android-drawable

我想在按下、聚焦和单击时更改按钮颜色,但我想我一定做错了什么,我的代码不起作用。有人会请教吗?谢谢!

这是我在 drawable 中的 soundbtn.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
        android:drawable="@drawable/sound_onpress_mdp" /> <!-- pressed -->
    <item android:state_focused="true"
        android:drawable="@drawable/sound_onpress_mdp" /> <!-- focused -->
    <item android:drawable="@drawable/sound" /> <!-- default -->
</selector>

然后我在布局中为 ImageButton 添加了背景:

<ImageButton
    android:id="@+id/imageSound"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/soundbtn"
    android:contentDescription="@string/image_desc"
    android:src="@drawable/sound" /> 

这是我的 Java 代码:

private ImageButton btnSound;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_game);

    btnSound =(ImageButton) findViewById(R.id.imageSound);
    btnSound.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            btnSound.setBackgroundResource(R.drawable.soundbtn);
        }
    });
}

最佳答案

尝试删除

 android:src="@drawable/sound" 

 btnSound.setBackgroundResource(R.drawable.soundbtn);

你只需要

 android:background="@drawable/soundbtn"

因为它调用具有目标可绘制对象的项目,如“按下”或“聚焦”。

关于ImageButton 颜色不改变 onPressed(), onFocus(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15284575/

相关文章:

android - 发送safetynet兼容性检查请求是否有配额限制

android - 无法在 gradle 上解析符号 MavenDeployment

android - 如何将样式应用于所有按钮而不是 ImageButtons?

android - 我应该使用什么 ImageButton 或 Button?

android - 使用 ffmpeg 将 Android 框架的 .raw 文件编码为 .png 文件格式

android - Radiobutton drawable 对 state_checked 没有反应

java - Android 9 中的可绘制按钮未显示

android - 如何将 Drawable 转换为位图?

java - 将图像从一个 ImageButton 传输到另一个

android - picasso - 将图像加载到适配器中的图像按钮