Android: long click on a button -> perform actions
Change return false;
to return true;
in longClickListener
You long click the button, if it returns true then it does the work. If it returns false then it does it's work and also calls the short click and then the onClick also works.
Initially when i implemented a longClick and a click to perform two separate events the problem i face was that when i had a longclick , the application also performed the action to be performed for a simple click . The solution i realized was to change the return type of the longClick to true which is normally false by default . Change it and it works perfectly .
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.
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.