Android Long Press Event Handle - Example



There may be situation in which your app needs to provide options to the user on long pressing a view. For example as in the messenger app, when you long press a conversation there will be a pop-up menu option to delete the conversation. Thankfully android has the View.setOnLongClickListener to handle it. In this post I will create an android application project with a simple text view on clicking the view, a toast 'Not Long Enough' is displayed and on long pressing the view a toast 'You have pressed it long' is displayed.

So lets start

1.Create an Android Application Project with any package name, any project name , activity as LogPress and layout file as activity_long_press.
2.First let us design the UI for the activity with a normal text view displaying “Long Press Me!!!”

activity_long_press.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".LongPress" >

<TextView
android:id="@+id/txtView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="center"
android:text="Long Press Me!!!!" />

</RelativeLayout>

3.Now in the activity file handle the text views onClick and onLongClick Events like the below code.

LongPress.java:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class LongPress extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_long_press);
  TextView txtView = (TextView) findViewById(R.id.txtView);
  txtView.setOnLongClickListener(new OnLongClickListener() {
   @Override
   public boolean onLongClick(View v) {
    // TODO Auto-generated method stub
    Toast.makeText(getApplicationContext(),
      "You have pressed it long :)", 2000).show();
    return true;
   }
  });
  txtView.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Toast.makeText(getApplicationContext(), "Not Long Enough :(",
      1000).show();
   }
  });
 }

}

4.Run the project by right-clicking project Run as → android application. The output should be similar to the one below when you long press the text view

Output: