I am currently having an issue with replacing a certain fragment within ViewPager with another. The fragment id like to replace is my \"Departments\" which has an Imagebutton id
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.
I think the point is to use a fragment as a container.
In your ViewPagerAdapter:
@Override
public Fragment getItem(int position) {
/*
* IMPORTANT: This is the point. We create a RootFragment acting as
* a container for other fragments
*/
if (position == 0)
return new RootFragment();
else
return new StaticFragment();
}
RootFragment layout should look like:
<FrameLayout xmlns: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:
public class RootFragment extends Fragment {
private static final String TAG = "RootFragment";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* Inflate the layout for this fragment */
View view = inflater.inflate(R.layout.root_fragment, container, false);
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
/*
* When this container fragment is created, we fill it with our first
* "real" fragment
*/
transaction.replace(R.id.root_frame, new FirstFragment());
transaction.commit();
return view;
}
}
Finally, you can replace fragments. For instance, inside your "real" fragment you could have a button:
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();
}
});
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:
https://github.com/danilao/fragments-viewpager-example