A simple solution is to create a small Fragment Utility class. This class should handle the showing and hiding of a fragment with some simple method calls. It should allow you to add the fragment to the back stack, or not, to add a tag for the fragment and to decide on your entrance and exit animations.
To do this, we first create the animations. We usually want slide in and out animations, mostly from the right hand side or from the bottom.
To create the slide in animation from the right hand side, we use a simple translate animation.
Here we are translating from xDelta of 100% to 0. For the slide out animation we simply reverse this.
We can repeat these type of animations for slide entrance and exit from differing sides.
To create the utility we make a class named FragmentUtil.
We first will create an enum called FragmentSlideAnimation to contain our entrance and exit animations. We then add a function to return the chosen animations.
We also want this class to handle fragments using the latest versions of Android, but also to support older versions using the v4 support jar.
This means that for each method we need to have a similar method for the v4 fragments.
Firstly we create a hide method. The function will take in the fragment to hide and the fragment manager or the fragment transaction. We can use overloading to create two methods with the same name but differing method signatures.
So next we want show the fragment. We are going to show all fragments on the content. We have a few options when showing a fragment.
- To use a entrance/exit animation
- To add to the back stack
- To set a tag for the fragment
If you notice, we didn't get the option for adding a tag. Well we have to do this with extra methods as Android uses overloading on the fragmentTransaction.add method to achieve this.
And that's it. We need to repeat this for v4 fragments and we're done. We can then extend the utility to handle showing fragments on differing layouts instead of just on the content.
You can find the code for this on my github.