Home >Java >javaTutorial >How Can I Dynamically Replace Hard-coded Fragments in Android?
Replacing Fragments Dynamically Within Activity Groups
Replacing fragments within an activity group can pose challenges. This article addresses the issue of swapping one fragment for another when the initial fragment is hard-coded in XML.
Solution
To dynamically replace a fragment, it must have been initially added dynamically. Here's how to achieve this:
// Create new fragment and transaction Fragment newFragment = new SectionDescriptionFragment(); FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction(); // Replace the existing fragment transaction.replace(R.id.book_description_fragment, newFragment); transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); transaction.addToBackStack(null); // Optional: Add to back stack for navigation // Commit the transaction transaction.commit();
Note:
The above is the detailed content of How Can I Dynamically Replace Hard-coded Fragments in Android?. For more information, please follow other related articles on the PHP Chinese website!