[android] Android: long click on a button -> perform actions

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!

This question is related to android

The answer is


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 .


Try using an ontouch listener instead of a clicklistener.

http://developer.android.com/reference/android/view/View.OnTouchListener.html


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.


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.