Activity as Container for Fragments

Reading Time: 2 minutes

Good practice in Android programming is to use Activity merely as a container and use Fragments for ALL UI elements, including the button you are clicking to change between them. For this purpose read as introduction.  Now, start new blank activity. Then add new Fragment and call it CentralFragment.


Delete most of unnecessary code so what is suppose to remain from all of the code is:

public class CentralFragment extends Fragment {

public CentralFragment() {

// Required empty public constructor


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

// Inflate the layout for this fragment

return inflater.inflate(R.layout.fragment_central, container, false);




Make change in remaining code with creating View object and returning it instead of inflater.

return inflater.inflate(R.layout.fragment_central, container, false);

View view = inflater.inflate(R.layout.fragment_central, container, false);
return view;


Then replace FrameLayout in fragment_central.xml to RelativeLayout. Also, we must give an id to the central fragment, for example:


In content_main.xml we should include following XML code so CentralFragment will take place. Delete all padding and put the following code for adding Fragment into content_main.xml:

<fragment android:id=”@+id/central_fragment”






And we can add two buttons that will be used to start Fragment1 and Fragment2 form CentralFragment.



Tagged with: ,

Leave a Reply

Your email address will not be published. Required fields are marked *