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

本秂侑毒 提交于 2019-12-05 14:56:22

问题


I have the following code which creates an ImageButton and plays a sound when clicked:

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!


回答1:


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.

This way it will allow other actions to also respond to the touch.




回答2:


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


来源:https://stackoverflow.com/questions/2617969/how-can-i-change-the-images-on-an-imagebutton-in-android-when-using-a-ontouchlis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!