In this example, we will be see how to use fragments to generate UI at runtime. We will be using two fragments to generate views to be displayed on a frame layout.
Steps to develop this can be summarized below -
Now, let’s begin the development...
We will be developing the app shown in the below screenshot.
Below is the MainActivity(Launcher Activity).
FragmentManager is a class that helps in Managing the fragments. We get an instance of this class from the method getFragment Manager().
Then we use FragmentTransaction object to start doing transactions with fragment manager. By transactions, we mean putting a view of fragment on a frame layout. In the next step you can see that tx.replace(R.id.fragment_place,new FragmentOne()) is doing the replacement. Finally we call commit() method to execute the transaction.
selecFrag() method is used to handle the clicks on the buttons at the top. Depending upon the button clicked, we create a new fragment of the respective button and display it on the frame layout.
Below is the layout for the MainActivity.class
We are using a LinearLayout with vertical orientation to host another Linear Layout with horizontal orientation. Apart from the two buttons, we also have a FrameLayout which will be hosting the Fragment Views.
Below is the class for first fragment which provides the view when the user clicks on the first button. We are overriding onCreateView() method in this class to inflate the view to be hosted inside the frame layout in the MainActivity.class
A Layout named as fragment_one.xml is being used to inflate the view.
Below is the layout for the fragment which is shown on the frame layout. It simply has one LinearLayout conatining an ImageView which holds an image.
Below is the class- FragmentTwo.class
This class serves the same purpose as the previous fragment class. Infact, there is no different between the two classes except for the different layouts which we need to show in the frame layout.
Below is the layout for fragment_two.class.It simply has one LinearLayout conatining an ImageView which holds an image.
Below are the Screenshots for the output.
1. When the App launches. The default fragment is displayed. Same Fragment is displayed when the user clicks on the button Fragment1
2. User clicking on second button - Fragment 2. This button displays the second fragment on the frame layout.