1

I've succesfully implemented CAB for ListView in Fragment and everything work just fine -> but when I hit back or when I change displayed fragment through navigation drawer, CAB stays opened. What I need to do is to close CAB in onDestroy method. I've tried this:

listView.clearChoices();
listView.cancelLongPress();

But it has no effect to CAB. Any solutions here?

ijby
  • 131
  • 3
  • 11

2 Answers2

7

I found pretty easy way how to handle this:

1) Make global variable of type ActionMode:

ActionMode actionMode = null;

2a) Assign ActionMode in onCreateActionMode() method:

@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
    getActivity().getMenuInflater().inflate(R.menu.action_mode, menu);
    actionMode = mode;
    return true;
}

2b) Also put this in onDestroyActionMode() method:

@Override
public void onDestroyActionMode(ActionMode mode) {
    actionMode = null;
}

3) Override onDestroy() method (you can also use onPause() if you want to close CAB every time fragment is paused, but this may be annoying to users):

@Override
public void onDestroy() {
    super.onDestroy();

    //Destroy action mode
    if(actionMode != null)
        actionMode.finish();
}

That's it, now every time you'll replace Fragment, it will cancel ActionMode.

ijby
  • 131
  • 3
  • 11
1

Something like this should do it for the back button:

@Override
public void onBackPressed() {
    actionmode.finish(); // Replace with reference to your CAB.
}

You can put the same command into your button logic.

javmarina
  • 493
  • 6
  • 17
JASON G PETERSON
  • 2,193
  • 1
  • 18
  • 19
  • Since ListView is in fragment, there's no onBackPressed(), but you gave me an idea - gonna post it as separate answer. – ijby Dec 16 '14 at 12:29
  • Ah, good point. Some workarounds to that here, in case your idea doesn't work out: http://stackoverflow.com/questions/5448653/how-to-implement-onbackpressed-in-android-fragments – JASON G PETERSON Dec 16 '14 at 12:33
  • 1
    Look at my answer to this question, it works now :) And it's easy to use and it gives you additional option to cancel CAB at anytime you need to. – ijby Dec 16 '14 at 12:37