Activity as Container for Fragments

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.

New-Fragment-To-be-Main-Fragment

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);

}

}

Code-that-Remains-in-Main-Fragment

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;

Create-View-object-in-Fragment-Central

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

Give-an-id-to-the-CentralFragment

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”

android:layout_height=”wrap_content”

android:layout_width=”wrap_content”

android:name=”cirvirlab.actcontainermanufragments.CentralFragment”>

</fragment>

XML-code-for-Including-CentralFragment

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

Two-Buttons-in-CentralFragment

 

Posted in android Tagged with: ,

Leave a Reply

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

*