Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

android - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...