Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnTouch works, but OnClickListener doesn't?

Tags:

I created a widget/control that I can reuse which I created by extending RelativeLayout. Then, in one of my Activities, I created a bunch of these widgets in a loop. However, I ran into an issue when I wanted to have each widget respond to a click.

I found that setting OnTouchListener works:

 this.setOnTouchListener(new OnTouchListener(){         public boolean onTouch(View arg0, MotionEvent arg1) {            //Triggers debug message         }            }); 

but OnClickListener doesn't:

  this.setOnClickListener(new View.OnClickListener(){         public void onClick(View v) {            //Doesn't trigger debug message           }      }); 

Why is this?

like image 264
tpow Avatar asked Mar 12 '11 15:03

tpow


People also ask

Why my setOnClickListener is not working?

You need to put the setOnClickListener in one of the activity callbacks. In your onCreate() method, move the button there and then setOnClickListener() . Show activity on this post.

What is the difference between onTouch and onClick Android?

Use OnTouchListener when you want to receive events from someone's finger on the screen. Use OnClickListener when you want to detect clicks.

How do I use OnClickListener?

In Android, the OnClickListener() interface has an onClick(View v) method that is called when the view (component) is clicked. The code for a component's functionality is written inside this method, and the listener is set using the setOnClickListener() method.

Which are the ways to set OnClickListener for button in Android?

To define the click event handler for a button, add the android:onClick attribute to the <Button> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.


2 Answers

You should make sure that the TouchListener is not 'consuming' the touch event. If you return true from the onTouch() method, Android will consider it consumed and not pass it on to the other various touch handlers (which I am assuming will include the ClickListener).

You should do:

this.setOnTouchListener(new OnTouchListener(){     public boolean onTouch(View arg0, MotionEvent arg1) {         //Triggers debug message         return false;     }        }); 
like image 97
nicholas.hauschild Avatar answered Oct 17 '22 18:10

nicholas.hauschild


Here are a few things to check to make sure your views are clickable:

View.setClickable() View.setEnabled() View.setFocusable() View.setFocusableInTouchMode() 

Depending on the exact behavior you hope to get, you'll need to set one or more of those to on. Since you are getting onTouch events, my guess is that you need to setClickable. But i'd have to see the view creation code to be sure.

like image 43
Nick Campion Avatar answered Oct 17 '22 17:10

Nick Campion