Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine OnClickListener and OnTouchListener for an ImageButton

I need to do something when the user clicks the ImageButton I've tried to create a static class that implements both OnClickListener and OnTouchListener

static class ClickListenerForScrolling implements OnClickListener, OnTouchListener  

that has the following methods:

@Override public void onClick(View v) 

and

@Override public boolean onTouch(View arg0, MotionEvent arg1) 

The whole idea behind this is to change the image source of the ImageButton when the user touches it, and perform a task when the user clicks this button. Can anybody give me a hint on how to do this?

like image 361
Tobias Moe Thorstensen Avatar asked Jul 20 '12 11:07

Tobias Moe Thorstensen


People also ask

How do I add OnClickListener?

Link the button from the XML by calling findViewById() method and set the onClick listener by using setOnClickListener() method. setOnClickListener takes an OnClickListener object as the parameter. Basically it's creating an anonymous subclass OnClickListener in the parameter.

How do I use onTouchEvent on Android?

After the Math. abs() calls, you're essentially testing if their finger is farther down the screen than it is across the screen. Store the initial down coordinates as member variables and set them during ACTION_DOWN . You declared two floats (touchX and touchY) inside the onTouchEvent method.

What is the purpose of setOnClickListener?

One of the most usable methods in android is setOnClickListener method which helps us to link a listener with certain attributes. While invoking this method a callback function will run. One can also create a class for more than one listener, so this can lead you to code reusability.


1 Answers

Since both actions consist of the gestures "put finger on screen - lift finger from screen" you can't determine if it was touch action or a click action. So if you implement both listeners on this image button, a touch/click will change the picture AND press the button. Not sure if there is a determined order of these events...

However, if you want to separate these events, you will either need to define to a different gesture to one of the actions (like wiping to change picture), or create different areas who handle the events, for example the image doesn't fit the whole button and the free area serves as button click area.

HTH

Update:

I figured out, that a TouchEvent is more general than a ClickEvent thus it is called first.

public abstract boolean onTouch (View v, MotionEvent event) 

This returns true, if the listener has consumed the event, false otherwise. So you can decide in your implementation if the Event should also be handled by OnClickListener, then just return false.

like image 162
Sven Menschner Avatar answered Sep 21 '22 10:09

Sven Menschner