l8gcqa
Last Updated: October 04, 2018
·
12.61K
· sapandiwakar

Replacing one fragment with another in Android dynamically

I needed to replace fragment in an Android application when I was using Tab bar and I needed to change fragment when tab bar is changed. At first, I defined the fragment statically in layout file and when I tried to change it dynamically I received an error. Then I found out that it is only possible to change those fragments defined dynamically via a FragmentTransaction. Replacing one fragment with another in Android dynamically describes how to replace fragments in Android programatically.

1 Response
Add your response

30871

Hi Sapan,

I started working with Android Fragments not so long ago. In the Fragment Manager I created the FragmentTransaction to add or remove the other elements. Currently using this code suggested by John Smith in Stackoverflow:
public void switchFragment(BaseFragment baseFragment) {
try {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.anim.slideinleft, android.R.anim.slideoutright);
if (getSupportFragmentManager().findFragmentById(R.id.homeframe) == null) {
ft.add(R.id.home
frame, baseFragment);
} else {
ft.replace(R.id.home_frame, baseFragment);
}
ft.addToBackStack(null);
ft.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
Sources:
https://stackoverflow.com/questions/5658675/replacing-a-fragment-with-another-fragment-inside-activity-group
https://hireessaywriter.org/write-me-an-essay.html
David

4 months ago ·