how to handle long click in Android

ewok picture ewok · Mar 6, 2012 · Viewed 17.6k times · Source

I am new to Android dev. The way I have been handling clicks has been by setting the android:onClick attribute in the manifest file for buttons. What I am wondering is the best way to handle long clicks in general. I have read about implementing onLongClick(), but is there a way to use handlers (like above), rather than having to extend View? It would be very helpful, as I would rather not have to rebuild my entire project with an extended View class.

EDIT

I should clarify. I have a ListView and I want to set what will happen when I long click on an element in the list. Each element in the list is a TextView. As per one of the answers, I have added the below code, and now I get a force close:

public class TwitterActivity extends ListActivity {
    List<String> tweets = new LinkedList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setListAdapter(new ArrayAdapter<String>(this, R.layout.layout, tweets));

            TextView view = (TextView) findViewById(R.id.ListTemplate);
            view.setOnLongClickListener(new OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    Toast toast = new Toast(TwitterActivity.this);
                    toast.setText("LongClick");
                    toast.show();

                    return true;
                }
            });

    //...
    }
}

Answer

Matt Wolfe picture Matt Wolfe · Mar 6, 2012

For a ListActivity if you want to respond to long clicks on the list elements do this:

public class TwitterActivity extends ListActivity {
    List<String> tweets = new LinkedList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setListAdapter(new ArrayAdapter<String>(this, R.layout.layout, tweets));
            ListView lv = getListView();
            lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){ 
                   @Override 
                   public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) 
                  { 
                       Toast.makeText(TwitterActivity.this, "LongClick", Toast.LENGTH_LONG).show();
                  } 
             }); 

    }
}

For a regular activity you could do something like this:

public class MyActivity extends Activity implements View.onLongClickListener {

   View myView = null;


   public void onCreate(Bundle state) {
      super.onCreate(state);
      setContentView(R.layout.my_activity);
      myView = findViewById(r.id.my_view);
      myView.setOnLongClickListener(this);
   }

   @Override
   public void onLongClick(View v) {
    //long clicked
   }

}