简体   繁体   English

使用OnTouchListener时,如何更改Android中ImageButton上的图像?

[英]How can I change the images on an ImageButton in Android when using a OnTouchListener?

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. 问题是我希望按下它时ImageButton上的图像会发生变化。 The OnTouchListener appears to be overriding the touch and not allowing the images to change. OnTouchListener似乎覆盖了触摸并且不允许图像更改。 As soon as I remove the OnTouchListener, the ImageButton swaps to a different image when pressed. 一旦我删除了OnTouchListener,ImageButton会在按下时切换到不同的图像。 Any ideas on how I can have the images change on the ImageButton while still using the OnTouchListener? 关于如何在仍然使用OnTouchListener时在ImageButton上更改图像的任何想法? Thank you very much! 非常感谢你!

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;
    }
});

I think the solution is simple: remove the return true from the ontouchlistener. 我认为解决方案很简单:从ontouchlistener中删除return true Since that blocks all further operations that respond to touch and input. 因为这会阻止所有响应触摸和输入的进一步操作。 Make it return false too. 让它也return false

This way it will allow other actions to also respond to the touch. 这样它将允许其他动作也响应触摸。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM