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

时间:2013-03-08 00:28:03

标签: android imagebutton android-ui 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);
        }
    });
}

1 个答案:

答案 0 :(得分:1)

尝试删除

 android:src="@drawable/sound" 

 btnSound.setBackgroundResource(R.drawable.soundbtn);

你只需要

 android:background="@drawable/soundbtn"

因为它调用了具有目标drawables的'pressed'或'focused'这样的项目。