Hiding/showing the contextual action bar programmatically
Asked Answered
E

2

5

My use case:

I have an activity with a ViewPager as its only view element, set up with three Fragments for its three pages (using a FragmentPagerAdapter). One of these fragments is a ListFragment, while the other two regular Fragments containing some infographics.

The list in the ListFragment allows "checking" elements, and checking elements brings up the contextual action bar, presenting a list of actions possible on the selected/checked items.

My problem:

When I select a couple of list items, the CAB shows up. But when I switch pages, the CAB stays visible, presenting the actions. To make matters worse, the ViewPager seems to sometimes destroy the view of the list fragment - hence selecting the actions throws a "java.lang.IllegalStateException: Content view not yet created" exception.

My questions:

  1. How do I get the CAB to disappear when the user moves away from the ListFragment page?
  2. (optional) How do I get the CAB to reappear when the ListFragment back is and some items are still checked.
Epigeal answered 22/2, 2013 at 7:50 Comment(0)
R
1

You need to first add a ViewPager.OnPageChangeListener with ViewPager.OnPageChangeListener to your viewPager.

In the onPageSelected method call a method in your ListFragment to dismiss your CAB.

EDIT:

To get the current active fragment you can use it's tag. The tag can be computated with this method:

private static String makeFragmentName(int viewId, int index) {
   return "android:switcher:" + viewId + ":" + index;
}

where viewId is the id of the viewpager and index the tab index (position)

Retroflexion answered 26/2, 2013 at 15:32 Comment(3)
How would you access the appropriate ListFragment from the ViewPager?Micco
I've edited the answer to add the information on how to access the fragmentRetroflexion
How come ViewPager.OnPageChangeListener is there twice? Is that a typo or is it supposed to mean something else?Dubai
A
0

You can also react to the fragment being hidden from inside the fragment by using the method setUserVisibleHint, as explained in https://mcmap.net/q/53706/-how-to-determine-when-fragment-becomes-visible-in-viewpager

Anglesey answered 27/1, 2014 at 8:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.