我有一个包含多个片段的活动。活动最初有片段,并在它有两个按钮。在点击该按钮,我必须通过新的片段来代替片段。每个片段都有不同的部件和替换当前的片段作为各种活动。
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 be done.
推荐我的想法。
您可以通过FragmentTransaction代替片段。
you can replace fragment by FragmentTransaction.
在这里,你走了。
请一个接口。
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.
//在您的片段。
public void showOtherFragment()
{
Fragment fr=new NewDisplayingFragment();
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.replaceFragment(fr);
}
希望这将工作!
Hope this will work!
注意:mContainerId是谁拿着里面的片段视图的ID。 你应该重写片段的onString()方法为好。
NOTE: mContainerId is id of the view who is holding the fragments inside. You should override Fragment's onString() method as well.