Search code examples
androidlistviewcheckboxactionbarsherlockspinner

Android ActionBar/ActionBarSherlock multiple choices spinner


I have a ListView containing items which belongs to one or more category. I would like, by clicking on an icon in the actionbar, to select and unselect theses categories. This way, the listView is refresh according to the categories selected.

Here is an example I found :

581753Screenshot20140110103007.png http://www.hostingpics.net/viewer.php?id=581753Screenshot20140110103007.png

For the moment, I found 2 solutions :

  • Adding a spinner with checkable items but it closes the menu at every selection/unselection
  • Create a ListView with cheackable items in a RelativeLayout and make it appears when the icon is clicked.

The second solution fits exactly with the UI expectations but I think there is a sort of multiple choices spinner solution.


Solution

  • A Spinner shows the drop down using a ListPopupWindow, you could use the same to show that multi choice item selection list:

    private void showPopup() {
        final ListPopupWindow lpw = new ListPopupWindow(this);
        lpw.setAdapter(/*Your adapter here*/);
        lpw.setAnchorView(mAnchor); // see below
        lpw.setContentWidth(/*specific value*/); // see below
        lpw.show();
        // this is required because the popup's `ListView` will not be available 
        // until the ListPopupWindow is actually shown.
        mAnchor.post(new Runnable() {
            @Override
            public void run() {
                lpw.getListView().setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
            }
        });
    }
    

    You could then call this method from the onOptionsItemSelected() callback when the right MenuItem is selected. There are two other things you need to take care:

    The mAnchor is a View that you need to insert in the Activity's layout in the top-right corner so the ListPopupWindow will show in the right position. For example, if you have as an Activity root:

    a RelativeLayout then mAnchor will be:

    mAnchor = new View(this);
    RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(0, 0);
    rlp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
    rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    mAnchor.setLayoutParams(rlp);
    // add mAnchorView first to the RelativeLayout
    

    a LinearLayout then mAnchor will be:

    mAnchor = new View(this);
    LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(0, 0);
    llp.gravity = Gravity.RIGHT;
    mAnchor.setLayoutParams(llp);
    // add mAnchorView first to the LinearLayout(assuming orientation vertical)
    

    and so on for other types of layouts.

    Secondly, you need to setup the width of the ListPopupWindow to a desired value. You'll need to adapt this value for different screen sizes and orientation(like phone-portrait and phone-landscape, different table sizes in portrait and landscape).