I want to use the same button to perform 2 different methods. One method when user single clicks it and a second method (different) when the user LONG clicks it.
I use this for the single short click (which works great):
Button downSelected = (Button) findViewById(R.id.downSelected); downSelected.setOnClickListener(new OnClickListener() { public void onClick(View v) { method(); } } });
I've tried to add a longClickListener but it didn't work.
Appreciate any ideas on how to solve this.
Thanks!
Long pressing lets you get some information, download photos from the web, edit pictures, and more.
When the user clicks a button, the Button object receives an on-click event. To make click event work add 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.
I've done it before, I just used:
down.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { // TODO Auto-generated method stub return true; } });
Per documentation:
public void setOnLongClickListener (View.OnLongClickListener l)
Since: API Level 1 Register a callback to be invoked when this view is clicked and held. If this view is not long clickable, it becomes long clickable.
Notice that it requires to return a boolean, this should work.
To get both functions working for a clickable image that will respond to both short and long clicks, I tried the following that seems to work perfectly:
image = (ImageView) findViewById(R.id.imageViewCompass); image.setOnClickListener(new OnClickListener() { public void onClick(View v) { shortclick(); } }); image.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { longclick(); return true; } });
//Then the functions that are called:
public void shortclick() { Toast.makeText(this, "Why did you do that? That hurts!!!", Toast.LENGTH_LONG).show(); } public void longclick() { Toast.makeText(this, "Why did you do that? That REALLY hurts!!!", Toast.LENGTH_LONG).show(); }
It seems that the easy way of declaring the item in XML as clickable and then defining a function to call on the click only applies to short clicks - you must have a listener to differentiate between short and long clicks.
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