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

cod*_*man 12 android imagebutton

我有以下代码创建一个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;
    }
});
Run Code Online (Sandbox Code Playgroud)

问题是我希望按下它时ImageButton上的图像会发生变化.OnTouchListener似乎覆盖了触摸并且不允许图像更改.一旦我删除了OnTouchListener,ImageButton会在按下时切换到不同的图像.关于如何在仍然使用OnTouchListener时在ImageButton上更改图像的任何想法?非常感谢你!

use*_*905 33

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;
    }
});
Run Code Online (Sandbox Code Playgroud)


Pet*_*rdk 4

return true我认为解决方案很简单:从 ontouchlistener 中删除。因为这会阻止响应触摸和输入的所有进一步操作。也做一下return false吧。

这样,其他操作也可以响应触摸。