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?
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.
Use OnTouchListener when you want to receive events from someone's finger on the screen. Use OnClickListener when you want to detect clicks.
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.
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.
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; } });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With