Replacing fragment dynamically in ViewPager using TabsAdapter
I am using ViewPager in combination with ActionBar tabs as shown here . I am using ActionBarSherlock for backward compatibility, so the parent activity extends SherlockFragmentActivity and child fragments extend SherlockFragment.
The solution works great for scrollable tabs, but now I want to dynamically change the fragment associated with one of the tabs.
I've read numerous SO answers on this topic (like here and here ), but I haven't found a clear explanation of how to dynamically change a fragment when using the ViewPager + TabsAdapter above.
Here's what I have now. When the user clicks a button on an existing fragment, I try to replace the fragment from the parent activity like this:
AnotherFragment fragment = new AnotherFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
int viewId = R.id.pager; // resource id of the ViewPager
int position = Constants.TAB_2; // tab pos of the fragment to be changed
String tag = "android:switcher:" + viewId + ":" + position;
ft.replace(viewId, fragment, tag);
ft.commit();
mTabsAdapter.notifyDataSetChanged();
It doesn't work, so I am missing something. I also tried to do this with nested fragments using getChildFragmentManager (), but ran into a problem as this function is not available without API 17, Android 4.2.
Thanks for any help!
source to share
I've made a small example that shows similar behavior. Hope you can reuse it.
I think the key is to use the fragment as a container and replace its "real" fragment using that.
For example, see how to navigate to another snippet:
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction trans = getFragmentManager()
.beginTransaction();
/*
* IMPORTANT: We use the "root frame" defined in
* "root_fragment.xml" as the reference to replace fragment
*/
trans.replace(R.id.root_frame, new SecondFragment());
/*
* IMPORTANT: The following lines allow us to add the fragment
* to the stack and return to it later, by pressing back
*/
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(null);
trans.commit();
}
});
You can check the whole example here:
source to share