The quick and easy guide to using Fragments.

Why are all the examples I find not straight forward?!

If you're anything like me, you don't read documentation thoroughly unless you absolutely have to. At the very least you might just need a quick code snippet to make something work, and sometimes StackOverflow or some huge blog post is a little much.

So here's the quick and easy way to implement fragments.

Step 1: You need a custom fragment class. Name it whatever you like, just replace "CustomFragment" in the code below.In this onCreateView function you need to initialize elements in your fragment and manipulate them how you want.
Ex: Connecting a button and changing the text.

However, you must use the syntax view.findViewById() referencing the view/XML you just inflated.



Step 2: You need to place this fragment view somewhere, and in turn you need to give an identifier to the view you're going to be sticking the fragment inside of. In this case the id is "mainContainer".

Step 3: Next is the easiest part, in your Activity or even another fragment use the code below to initialize a fragment, start a FragmentTransaction and commit the transaction. If you want the user to be able to press the back button and get back to your original view or activity you sent this from, keep the addToBackStack(null) line, if not, remove it.



Done! Enjoy using fragments.