我想在按下、聚焦和单击时更改按钮颜色,但我想我一定做错了什么,我的代码不起作用。有人会请教吗?谢谢!
这是我在 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/