Attaching Fragment to Activity dynamically in Runtime:
To attach fragment dynamically in runtime, we have a set of steps to follow.
1) Create a ViewGroup inside the Activity and provide id. This is the ViewGroup, which will be replaced by Fragment later.
2) In Activity, we have FragmentManager, which is responsible for attaching and removing fragments to Activity. We can get the object of FragmentManager by calling getSupportFragmentManager() method
3) FragmentTransaction – attaching and removing a fragment to Activity is called a transaction. FragmentTransaction is the class responsible for all transactions. To get object of FragmentTransaction, we call a method from FragmentManager object called beginTransaction()
4) Once we have FragmentTransaction object, we will add the Fragment by calling add(resourceId, fragment object) method
5) Commit the transaction.
Ex:
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
TestFragment fragment = new TestFragment();
ft.add(R.id.container, fragment);
ft.commit();
Create an Android application to attach a fragment to Activity when a button is clicked in Activity