Fragments are ways by which you can create multiple views in a single Activity, to avoiding to create multiple activities. You can add / remove fragments while the activity is running.
You can create a fragment in 2 ways: - static using XML and dynamic using programmatically
XML:
- Create 2 fragment classes using the wizard. This will create a class that extends Fragment and create the layout xml accordingly.
- headerFragment
- ArticleFragment.
- Now add the 2 fragments in the main activity XML file as below.
<fragment
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="@+id/headline_fragment"
android:layout_weight="1"
android:name="io.ctrlspace.fragmentexample.HeadlineFragment"> </fragment>
<fragment
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="@+id/article_fragment"
android:layout_weight="1"
android:name="io.ctrlspace.fragmentexample.ArticleFragment"> </fragment>
Now this is not of much use since we add these in static xml, often we may need to add dynamically fragments based on runtime logic.
Programmatically:
- Create a simple Empty Activity - say MainActivity.
- In the main Activity layout file, add a layout to hold the fragments, say a frame layout
- Now create a Fragment using Android studio - call it as HomeFragment. This will create a Java class that extends Fragment and a fragment layout file.
- Add some content for the fragment in the layout design to identify that its a fragment content, say add a text box with a text inside first fragment.
- In the main Activity add the following code.
- Get the FragmentManager instance
- Start the transaction of the fragment manager.
- Add or replace the fragment using the add / replace method in the fragment transaction, pass the fragment container and the fragment to be added or replaced to this method.
- Commit the transaction.
public static FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
if(findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
HomeFragment homeFragment = new HomeFragment();
fragmentTransaction.add(R.id.fragment_container, homeFragment, null);
fragmentTransaction.commit();
}
}
Fragment to Activity communication is handled in a different way - you can view the source code for this here.