Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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!

like image 598
codeman Avatar asked Apr 11 '10 17:04

codeman


People also ask

How do you add a picture to ImageButton?

In android, we can add an image to the button by using <ImageButton> attribute android:src in XML layout file or by using the setImageResource() method. In android, we can create ImageButton control in two ways either in the XML layout file or create it in the Activity file programmatically.

What are image buttons?

Displays a button with an image (instead of text) that can be pressed or clicked by the user. By default, an ImageButton looks like a regular Button , with the standard button background that changes color during different button states.

Can you add text to an ImageButton android?

Answer: You can not display text with imageButton . Method that tell in Accepted answer also not work. If you use android:drawableLeft="@drawable/buttonok" then you can not set drawable in center of button . If you use android:background="@drawable/button_bg" then color of your drawable will be changed.


1 Answers

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;
    }
});
like image 192
user632905 Avatar answered Oct 11 '22 09:10

user632905