What we are going to do :
A View with a Button. When we click that Button a fragment is being added dynamically in our View. We click again and the fragment is being dynamically removed.
One Activity and one Fragment. In the Activity's layout we add two layout objects. That's a Button and a FrameLayout.
In Fragment's layout we have a TextView that contains just text in a color background
So the code for the Activity's and Fragment's layout is:
Fragment's Layout :
Note the android:id = "@+id/fragment_container_1" in the Activity's layout which is an identifier for our fragment. When we make Transactions like add we refer to a fragment by id.
Activity and Fragment :Fragment Class : is a typical Fragment class as we have seen it before
Activity Class : onClick() begins Transaction. If state is null then we add and commit the fragment else we need to remove and commit again.
So the code is :