3

My question is simple: How do I use long click to let the users select items from the ListView ? So far, I only know how to detect 'short' clicks and take appropriate actions.

Also, I would like to display a check mark on the selected item. How can that be done ?

An SO User
  • 24,612
  • 35
  • 133
  • 221

3 Answers3

2

Answered in https://stackoverflow.com/questions/12090394/i-cant-get-longclick-to-work-on-listactivity :

// Optional, added if done from ListActivity (or possibly ListFragment)
ListView lv = getListView();
// Set on this if overriding OnItemLongClickListener, otherwise use an anonymous inner function
lv.setOnItemLongClickListener(this);
VonL
  • 227
  • 2
  • 13
2

Simple : OnLongClickListener

Then you need to manually remember what is selected or not. You need to notify the list from the changes and do something in the getView method of you adapter.

It would be a good practice to use the Contextual ActionBar mode to interact with all item at once, see here.

Stephane Mathis
  • 6,542
  • 6
  • 43
  • 69
2

It works the same way as the onClickListener, just instead you're checking the onLongClickListener. So you'd have this kind of structure:

your_view.setOnLongClickListener(new View.OnLongClickListener() {
  public boolean onLongClick(View v) {
    ...
  }
});

If you want to display a check mark, in my opinion the best way is defining your own row layout, where you just define a CheckBox at the right side the content of the row. This way, instead of passing the ArrayAdapter some Android layout, you'd specify your new layout, something like:

your_adapter = new ArrayAdapter(context, R.layout.your_new_layout, initial_rows);
nKn
  • 13,691
  • 9
  • 45
  • 62
  • If in my layout if I keep a check box with visibility `GONE`, and display it on long click, will it work ? – An SO User Jan 28 '14 at 18:35
  • You need to call notifyDataSetChanged on you adapter, then the getView method will be called for every visible row, you can then do everything you can like displaying a checkbox, change the background color, etc. – Stephane Mathis Jan 28 '14 at 18:37
  • Sure, simply declare the `onLongClickListener` inside your overriden `getView()` method. The second parameter of that method (usually called `convertView`) is (talking very vaguely) the layout of every row. You could simply get the `CheckBox`'s view by using `convertView.findViewById(R.id.my_checkbox)`, and afterwards you can do anything you want, set its visibility VISIBLE, GONE... – nKn Jan 28 '14 at 18:38
  • @NKN yeah, I get the gist . And Thank you Stephane for the addition =) However, remembering what is selected will be manual task, right ? – An SO User Jan 28 '14 at 18:39
  • Yes, a list of integer is enough, just save the row number. – Stephane Mathis Jan 28 '14 at 18:51