-4

How to change the whole view of a fragment with other fragment !!

Or how to close the current fragment with another fragment, please explain with layout also

Thanks in advance...

mayur saini
  • 209
  • 7
  • 17

3 Answers3

0
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentlayout,new fragment()).commit()

This will help you replace your existing fragment in view with id FragmentLayout with a new fragment().

ThankYou i hope this was helpful.

Sumanth Jois
  • 3,146
  • 4
  • 27
  • 42
0

You can either add or replace fragments in your activity. Create a FrameLayout in activity's layout xml file.

Then do this in your activity to replace fragment. You can use same code each time you want to replace one fragment with other.

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

If you want to add fragment instead of replace then do this:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

When you want to replace added frogment with anu other fragment then you have to remove previous fragment first (or you can hide previous fragment; depends on your requirement). See following code:

Fragment fragment = getSupportFragmentManager().findFragmentByTag(YOUR_FRAGMENT_STRING_TAG);
if(fragment != null)
    getSupportFragmentManager().beginTransaction().remove(fragment).commit();

See following related questions on SO:

Difference between add(), replace(), and addToBackStack()

Basic difference between add() and replace() method of Fragment

Difference between add() & replace() with Fragment's lifecycle

Or see my answer to a similar question:

How to start Fragment from an Activity

Community
  • 1
  • 1
0

First you take one Framelayout in Your Activity where you add fragment.

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.framelayout,fragment_1);
transaction.addToBackStack(null);
transaction.commit();

When you replace first fragment with second one you write, just change fragment_1 to fragment_2

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.framelayout,fragment_2);
transaction.addToBackStack(null);
transaction.commit();
Gundu Bandgar
  • 2,593
  • 1
  • 17
  • 21