Handling Long Clicks with setOnLong ClickListener

A long-click is a special type of click available on the Android platform. Basically, a long-click event is when a user clicks on a control for about one second. This type of click is handled separately from a regular, "short" click.

To handle long-clicks, you need to implement the View.OnLongClickListener class and pass it into the ImageButton control's setOnLongClickListener() method. OnLongClickListener has one required method you must implement: onLongClick(). Here is a sample implementation of OnLongClickListener for the avatar ImageButton control:

avatarButton.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // TODO: Launch Image Picker and Save Image as Avatar return false;

The onLongClick() method looks much like the onClick() method of the OnClickListener class. However, it has a return value, which should be true if long-click events are handled.

Take a moment to try out clicks and long-clicks with an ImageButton control:

1. Navigate to the QuizSettingsActivity.java class file and add a click listener and a long-click listener to the ImageButton_Avatar control.

2. Within the onClick() method of OnClickListener, add a Toast message that says Short click.

3. Within the onLongClick() method of OnLongClickListener, add a Toast message that says Long click.

4. Save your work and re-launch the application. Click the avatar ImageButton control on the settings screen and note when click and long-click events occur. ▲

+4 -2


    How to create setonlongclicklistener in android?
    3 years ago
    How to handle a long click listener?
    11 months ago

Post a comment