使用 OnTouchListener 时,如何更改 Android 中 ImageButton 上的图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2617969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I change the images on an ImageButton in Android when using a OnTouchListener?
提问by codeman
I have the following code which creates an ImageButton and plays a sound when clicked:
我有以下代码,它创建一个 ImageButton 并在单击时播放声音:
ImageButton SoundButton1 = (ImageButton)findViewById(R.id.sound1);
SoundButton1.setImageResource(R.drawable.my_button);
SoundButton1.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN ) {
mSoundManager.playSound(1);
return true;
}
return false;
}
});
The problem is that I want the image on the ImageButton to change when you press it. The OnTouchListener appears to be overriding the touch and not allowing the images to change. As soon as I remove the OnTouchListener, the ImageButton swaps to a different image when pressed. Any ideas on how I can have the images change on the ImageButton while still using the OnTouchListener? Thank you very much!
问题是我希望 ImageButton 上的图像在您按下它时发生变化。OnTouchListener 似乎覆盖了触摸并且不允许图像更改。一旦我移除 OnTouchListener,ImageButton 就会在按下时切换到不同的图像。关于如何在仍然使用 OnTouchListener 的同时更改 ImageButton 上的图像的任何想法?非常感谢!
采纳答案by Peterdk
I think the solution is simple: remove the return true
from the ontouchlistener. Since that blocks all further operations that respond to touch and input. Make it return false
too.
我认为解决方案很简单:return true
从 ontouchlistener 中删除。因为这会阻止所有响应触摸和输入的进一步操作。也做吧return false
。
This way it will allow other actions to also respond to the touch.
通过这种方式,其他动作也可以响应触摸。
回答by user632905
SoundButton1.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN ) {
mSoundManager.playSound(1);
btnmode.setImageResource(R.drawable.modeitempressed);
}
elseif (event.getAction() == MotionEvent.ACTION_UP ) {
btnmode.setImageResource(R.drawable.modeitemnormal);
}
return false;
}
});