Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: long click on a button -> perform actions

Tags:

android

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!

like image 423
Lior Iluz Avatar asked Dec 09 '10 20:12

Lior Iluz


People also ask

Which function is used for long press on Android?

Long pressing lets you get some information, download photos from the web, edit pictures, and more.

Which are the ways to handle onClick event of button?

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.


2 Answers

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.

like image 161
blindstuff Avatar answered Oct 11 '22 02:10

blindstuff


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.

like image 43
mklopfer Avatar answered Oct 11 '22 03:10

mklopfer