Here’s the thing. When showing a preference view in a new Activity and loading the XML preference layout within a Fragment, the problem is when you call addPreferencesFromResource(), the Fragment shows a blank view.

No Exceptions, no warnings. Nada.

I have no idea why, but calling getSupportActionBar() solves this problem. Without calling the action bar method, does not seem to exist hence replacing it with a Fragment will result in nothing since there is nothing to replace in the first place.

I thought that creating a custom method in my Activity class where I can change the visibility of a MenuItem and accessing it from the Fragment would work. Sadly, it did not.

It seems that the Fragment class has a method called setHasOptionsMenu(boolean) and you need to call that from within the onCreateView() method in order to be able to manipulate MenuItems from within onCreateOptionsMenu().

So this is how a sample Fragment class will look like.

This code looks for the MenuItem and hides it.

This one seems to hassle developers who have just started using fragments. Take this scenario for example:

Main Container > View Pager > Fragment objects

The problem is when I put in 2 ViewPager objects dynamically in the main container via the FragmentManager and FragmentTransaction classes respectively. The option addToBackStack() is also included. Now, after the back key is pressed, the previous ViewPager should be displayed.

However, nothing is shown and that left me scratching my head for quite a few hours. The solution is to pass a ChildFragmentManager instance to the FragmentStatePagerAdapter constructor. Do not use FragmentManager as that will make it blank.

Also, make sure your adapter uses FragmentStatePagerAdapter instead of FragmentPagerAdapter.

With those 2 requirements on hand, your ViewPager should be displayed no matter where they are in the FragmentManager’s pop stack.

Related Posts Plugin for WordPress, Blogger...