Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a Fragment on button click of that fragment?

I have an activity containing multiple fragments. Activity initially have fragment and in it have two buttons. Upon clicking this button I have to replace the fragment by new fragment. Each fragment has various widgets and replace the current fragment as various events.

This is my problem. How can I achieve this?

Suggest me ideas.

like image 514
Top Cat Avatar asked Jan 20 '14 07:01

Top Cat


People also ask

How do I replace a fragment with another fragment?

Use replace() to replace an existing fragment in a container with an instance of a new fragment class that you provide. Calling replace() is equivalent to calling remove() with a fragment in a container and adding a new fragment to that same container. transaction.

Can fragments be reused?

Understanding Fragments Using the support library, fragments are supported back to all relevant Android versions. Fragments encapsulate views and logic so that it is easier to reuse within activities. Fragments are standalone components that can contain views, events and logic.


Video Answer


1 Answers

you can replace fragment by FragmentTransaction.

Here you go.

Make an interface.

public interface FragmentChangeListener 
{
    public void replaceFragment(Fragment fragment); 
}

implements your Fragment holding activity with this interface.

public class HomeScreen extends FragmentActivity implements
        FragmentChangeListener {


         @Override
         public void replaceFragment(Fragment fragment) {
            FragmentManager fragmentManager = getSupportFragmentManager();;     
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(mContainerId, fragment, fragment.toString());
            fragmentTransaction.addToBackStack(fragment.toString());
            fragmentTransaction.commit();   
    }

}

Call this method from Fragments like this.

//In your fragment.

public void showOtherFragment()
{
       Fragment fr=new NewDisplayingFragment();
             FragmentChangeListener fc=(FragmentChangeListener)getActivity();
             fc.replaceFragment(fr);
}

Hope this will work!

NOTE: mContainerId is id of the view who is holding the fragments inside. You should override Fragment's onString() method as well.

like image 51
Ahmad Raza Avatar answered Sep 23 '22 09:09

Ahmad Raza