How implementate two fragments in an Activity

To start with this project will create a new blank one, once we create the new fragments, this is to easy, click in the tool bar, file,new fragment, blank fragment like this:

In this way, android studio will create a java class and a xml with the layout of this fragment ready to be used. Now let’s difference the fragments changing the backgroundColor and the text, open the layouts first I will add change the text in both of then and add the properties of background colour like this:

Add this to the principal Layout to set a background colour:

then add a textview and personalize, it this is my layout:

As you can see I changed the text to “You are in the fragment 1” and the colour of the text, do the same with in a second fragment, once this done, let’s to do code in the MainActivity, first lest start with the buttons

At first of the class:

And then inside of OnCreate():

To start the fragment layout with the first one we have to call the SupportFragmentManager to assign it, so we call the class we did fragment 1 and add to the fragment layout that we called container:

If we launch our app now, the buttons won’t do nothing but the first fragment will appear on the screen so let’s add the listener to the buttons with this, start with a switch to identify the event, if the event is the first button then replace the current fragment for the first one, with the transaction.

With this listener we just added the functionality to the buttons, and that is already done we have an activity with two fragments

You can download the source here Fragments