Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle long tap on ListView item?

How can I catch such event? onCreateContextMenu is quite similiar, but I don't need menu.

like image 287
LA_ Avatar asked Jun 01 '11 18:06

LA_


2 Answers

It's hard to know what you need to achieve. But my guess is that you want to perform some acion over the item that receives the long click. For that, you have two options:

  • add an AdapterView.OnItemLongClickListener. See setOnItemLongClickListener.

.

listView.setOnItemLongClickListener (new OnItemLongClickListener() {
  public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
    //do your stuff here
  }
});
  • if you are creating a custom adapter, add a View.OnLongClickListener when creating the View in the method Adapter#getView(...)
like image 200
Aleadam Avatar answered Nov 17 '22 12:11

Aleadam


Normally, you'd associate a long click on a list view with a context menu, which you can do by registering the listView with Activity.registerForContextMenu(View view) to give a more consistent user interface experience with other android apps.

and then override the onContextItemSelected method in your app like this:

@Override
public void onCreate(Bundle savedInstanceState) {
    listView = (ListView) findViewById(R.id.your_list_view);
    registerForContextMenu(listView);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle(getString(R.string.menu_context_title));
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.your_context_menu, menu);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

    switch (item.getItemId()) {
    case R.id.some_item:
        // do something useful
        return true;
    default:
        return super.onContextItemSelected(item);
    }

The position in the list is also held in info.id

If you just want to capture the long click event, then I think what Snicolas is suggesting would work.

like image 41
Mark Fisher Avatar answered Nov 17 '22 12:11

Mark Fisher