Search code examples
androidandroid-listview

enter multi-choice mode with nothing selected


Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially.

What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes).

I've also tried this in other apps (gmail), and it works the same way.

Is there a way to be in multi-select mode, with no items selected?


Solution

  • It's very hacky, but I've done this by having an item selected, but making it look like it's not selected, by making the background temporarily transparent. When an item is then selected by the user, the secretly-selected item is deselected and the background restored to normal. Or, if it's the secretly-selected item which is selected (thus deselecting it), I reselect it, then set a boolean to stop it happening again.

    I also had to use a counter in onItemCheckedStateChanged, as I was changing the checked state of the secret item from within that callback, resulting in a loop.

    Probably not an ideal solution for all cases, but I don't think there's another way to do it at the moment, since AbsListView can't easily be extended.

    Edit: if the screen orientation changes while the selected state of the selected item is hidden, it will suddenly be shown as being selected, so you have to make sure to save the fact that it should be hidden, and restore it after the listview is recreated. I had to use the View post() method to ensure the restoration happened after the listview had finished redrawing all its child items after the configuration change.

    Edit: another potential issue is if the user tries to carry out an action while there are supposedly no items selected. As far as the application knows there is an item selected so it will carry out the action on that item, unless you make sure it doesn't.