Replacing Fragments Within Viewpager
Solution 1:
I think the point is to use a fragment as a container.
In your ViewPagerAdapter:
@Overridepublic Fragment getItem(int position) {
/*
* IMPORTANT: This is the point. We create a RootFragment acting as
* a container for other fragments
*/if (position == 0)
returnnewRootFragment();
elsereturnnewStaticFragment();
}
RootFragment layout should look like:
<FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/root_frame" ></FrameLayout>
And directly, you fill it with your first "real" fragment:
publicclassRootFragmentextendsFragment {
privatestaticfinalStringTAG="RootFragment";
@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* Inflate the layout for this fragment */Viewview= inflater.inflate(R.layout.root_fragment, container, false);
FragmentTransactiontransaction= getFragmentManager()
.beginTransaction();
/*
* When this container fragment is created, we fill it with our first
* "real" fragment
*/
transaction.replace(R.id.root_frame, newFirstFragment());
transaction.commit();
return view;
}
}
Finally, you can replace fragments. For instance, inside your "real" fragment you could have a button:
btn.setOnClickListener(newOnClickListener() {
@OverridepublicvoidonClick(View v) {
FragmentTransactiontrans= 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, newSecondFragment());
/*
* 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();
}
});
I've developed an example application that shows a similar concept. You could replace a fragment inside a ViewPager without changing to a new Activity. The code is available in:
Solution 2:
I'm assuming you want the Engineering
fragment to be on a completely new page, because you aren't using it in your ViewPagerAdapter
. If that's the case, create a new Activity
, with your Engineering
fragment in the layout, and launch the Activity
from the engineeringButton
click.
The problem is you are trying to shove your Engineering fragment into the View hierarchy of R.layout.activity_departments
, and there is (hopefully) no ViewPager
in there, hence the error.
Post a Comment for "Replacing Fragments Within Viewpager"